Javascript Function get elements contents - javascript

I was using a listener to trigger a certain code:
$(".item-actions > .like-button").click(function (e) {
oid = $(this).parent().attr('data-oid');
alert(oid);
});
Now instead of a listener I'm simply calling the function on the HTML.
CLICK
I'm having problems getting the element's content, and parent content as I'm not able to use $(this) to select them. How can I do the same I was doing with the function?
I first tried this which didn't work:
function alertOID() {
oid = $(this).parent().attr('data-oid');
alert(oid);
}
How can this be done?

Is it what you are looking for?
<input class="like-button" onClick="alertOID.call(this);">

on .like-button html onclick event call alertOID() like this alertOID(this)
<input class="like-button" onClick="alertOID.call(this);">
instead of
<input class="like-button" onClick="alertOID.call();">
and change alertOID like this
function alertOID(element) {
oid = $(element).parent().attr('data-oid');
alert(oid);
}

Related

How to get element from DOM and set onclick event?

I have this html element:
<table id="miniToolbar">
<tbody>
<tr><td>
<button id="btnStrView" type="button" onclick='parent.ExecuteCommand()' class="button_air-medium">
<img id="streetView" class="miniToolbarContant" src="../stdicons/streetview-icon.png"></button>
</td></tr>
<tbody>
</table>
as you can see inside button I have on click event:
onclick='parent.ExecuteCommand()'
And I have this JS function:
function isMenuItemMasked(item)
{
var funcId = '75';
var elem = document.getElementById('btnStrView');
return false;
}
as you can see inside function I have variable called funcId.
I need to put this funcId to the on click event:
onclick='parent.ExecuteCommand('75')'
After I fetch element and put it inside elem variable how do I put funcId as parameter to parent.ExecuteCommand()?
I think you want to set the function argument dynamically. Without using external libraries I would do as follows:
function runSubmit() {
var value = document.getElementById("text").value;
document.getElementById("run").addEventListener('click', function() {
func(value);
});
}
function func(value) {
console.log(value);
}
<input id="text" type="text">
<input type="submit" value="Setup Param" onclick="runSubmit()">
<input id="run" type="submit" value="Run with param">
How to use this: When you run the snippet, you will see a text input, a Setup Param button and a Run with param button. Insert something in the text input and click Setup Param. After, click on Run with param to see the effect
The input text contains the string that will be used as parameter for func(value). The update of #run button callback is triggered by the "Setup param", through the runSubmit() callback. This callback adds to the #run element a listener for the 'click' event, that runs a function with the parameter fixed when event occurs.
This is only a MCVE, you should adapt it to your case scenario.
Mh... Actually #jacob-goh gave you this exact solution in a comment while I wrote this...
you can use jquery to call you function from inside the function and pass your variable to that function.
function isMenuItemMasked(item)
{
var funcId = "75";
$(document).ready(function(){
$("#btnStrView").click(function(){
parent.ExecuteCommand(funcId);
});
});
}
function ExecuteCommand(your_var){
alert(your_var);
//your code
}

Add onclick to element, but keep current onclick event

Is it possible to add a javascript event to a DOM element that already has a onclick event, but I want to keep that event property.
I have radio buttons like this:
<input type="radio" name="checkout-payment" value="56" id="checkout-payment-56" class="checkout-radio checkout-payment-radio checkout-payment-radio" onclick="paymentChanged(this);" />
in which I want to add
window.location.href=window.location.href
while keeping the original onclick, but I have no access to the html, I can only modify through javascript.
so my desired code will be
<input type="radio" name="checkout-payment" value="56" id="checkout-payment-56" class="checkout-radio checkout-payment-radio checkout-payment-radio" onclick="paymentChanged(this); window.location.href=window.location.href" />
Wrap the
window.location.href=window.location.href
in function, lets call it
onRadioButtonClick()
then, just do
var self = this; //keep the context of the file
$("[name=checkout-payment]").on('click', function () {
onRadioButtonClick.call(self); //call the method with the normal context.
//continue code..
});
You could try:
var curHandler = $('#checkout-payment-56').attr("onclick");
$('#checkout-payment-56')[0].onclick = null;
$('#checkout-payment-56').click(function () {
window.location.href=window.location.href;
});
I actually found out there was a much simpler way to acheive my desired result.
$( '.webshop-checkout input[type="radio"]' ).click(function() {
location.reload(true);
});
i am sorry i was not clear in my original post, and it has been edited.
If you want to add this to every .webshop-checkout input[type="radio"], you could do it that way:
$('.webshop-checkout input[type="radio"]').click(function(){
window.location.href=window.location.href;
});
JS Fiddle Demo
$("#checkout-payment-56" ).bind( "click", function(evt) {
console.log('that works');
//sessionStorage.setItem(evt.target.id,evt.target.className);
});

passing event data dynamically in jquery

Please refer below HTML
<div class="Icon">
<span>
<img src=""/>
</span>
</div>
I am adding class "bootstrap-modal" dynamically to above IMG tag when it is clicked.
$(".Icon img").on("click", function (e) {
var data="some object";
$(this).addClass("bootstrap-modal");
});
Then i have one more click event for bootstrap-modal class like below
$(document).on('click',"bootstrap-modal" function (e,data) {
//here i need to get data object
});
how to pass data object from img click event to bootstrap-modal click event?
That means I need to get some values from previous click handler ?
How can I do this ?
Save it in data:
$('.Icon img').on('click', function(e) {
var data = 'some object';
$(this).addClass("bootstrap-modal").data('test', data);
});
$('.Icon').on('click', '.bootstrap-modal', function(e, data) {
var data = $(this).data('test');
});
FYI: Since you use the newest version of jQuery, you'd better use on method with event delegation instead of deprecated live. Here .Icon is supposed to be a static parent element of .bootstrap-modal.

javascript onclick change onclick to new function

I need to be able to change the onclick event of an id so that once it has been clicked once it executes a function which changes the onclick event
Here is my code:
Javascript:
function showSearchBar()
{
document.getElementById('search_form').style.display="inline";
document.getElementById('searchForm_arrow').onclick='hideSearchBar()';
}
function hideSearchBar()
{
document.getElementById('search_form').style.display="none";
document.getElementById('searchForm_arrow').onclick='showSearchBar()';
}
and here is the HTML:
<!-- Search bar -->
<div class='search_bar'>
<img id='searchForm_arrow' src="images/icon_arrow_right.png" alt=">" title="Expand" width="10px" height="10px" onclick='showSearchBar()' />
<form id='search_form' method='POST' action='search.php'>
<input type="text" name='search_query' placeholder="Search" required>
<input type='image' src='images/icon_search.png' style='width:20px; height:20px;' alt='S' >
</form>
</div>
Thanks
Change your code in two places to reference the new functions directly, like:
document.getElementById('searchForm_arrow').onclick=hideSearchBar;
Can you try this,
function showSearchBar()
{
if(document.getElementById('search_form').style.display=='none'){
document.getElementById('search_form').style.display="inline";
}else{
document.getElementById('search_form').style.display="none";
}
}
You were nearly right. You are settingthe onclick to a string rather than a function. Try:
in showSearchBar()
document.getElementById('searchForm_arrow').onclick=hideSearchBar;
in hideSearchBar()
document.getElementById('searchForm_arrow').onclick=showSearchBar;
You do not need to create two function.
Just create one function and using if condition you can show and hide the form tag..
function showSearchBar()
{
if(document.getElementById('search_form').style.display=='none'){
document.getElementById('search_form').style.display=''; // no need to set inline
}else{
document.getElementById('search_form').style.display='none';
}
}
function searchBar(){
var x = document.getElementById('search_form').style.display;
x = (x == 'inline') ? 'none' : 'inline';
}
You can wrap up both functions into one by adding a check to the current condition of the element and applying your style based on that condition. Doesn't actually change the function but doesn't need to as there is now only one functon performing both actions.
With javascript you can check and perform opration
function SearchBarevent()
{
if(document.getElementById('search_form').style.display=='none'){
document.getElementById('search_form').style.display="inline";
}else{
document.getElementById('search_form').style.display="none";
}
}
or if you may go for jquery there is better solution toogle
Like:
$("#button_id").click(function(){
$( "#search_form" ).toggle( showOrHide );
});
Fiddle is example
Here is an option that uses jQuery:
$('#searchForm_arrow').click(function() {
$('#search_form').slideToggle();
});
http://jsfiddle.net/PuTq9/

Getting element id with jquery

The code should print the id of the selected div but it does not. I did not find the error. Thanks for help.
HTML
<body>
<div id="form_area">
<div>
<button onclick="return add_row();" style="width:100%;">Add Row</button>
</div>
</div>
</body>
Javascript
$(document).ready(function() {
$('#form_area div').click(function(e) {
console.log($(this).attr('id'));
});
});
function add_row() {
var random_id = Math.floor((Math.random() * 1000) + 1);
$('#form_area').prepend('<div id="' + random_id + '" class="form_row"></div>');
}
Ok, I think I understand what you are missing. You are trying to log the ID after adding a row using add_row function,
.form_row is added dynamically to the DOM. So when executing $('.form_row').click(, there is no .form_row to bind the handler. The below way of using .on method binds the handler to #form_area and executes the handler only when the click event is from .form_row
$('#form_area').on('click', '.form_row', function () {
console.log(this.id);
});
$('#form_area div') selects the div inside the div #form_area which doesn't have an ID
Below comment in html shows which div is selected,
<div id="form_area">
<div> <!-- $('#form_area div') selects this div-->
<button onclick="return add_row();" style="width:100%;">Add Row</button>
</div>
</div>
To access id use 'on' as your div is dynamically generated:
$(document).ready(function() {
$('#form_area').on('click', '.form_row', function () {
console.log(this.id);
});
});
Try console.log($('#form_area div').attr('id'));
Firstly, you have jQuery - you should use that to register your event handlers instead of using obsolete, error prone inline event handlers.
Secondly, your button handler is inside #formarea and so is also triggering the click handler since the button's parent has no ID. This is probably not desired.
Thirdly, your event handlers need to be delegated because you're trying to catch events on dynamically added elements.
So, remove the onclick attribute and add this:
$('#formarea button').on('click', addRow);
$('#formarea').on('click', '.form_row', function() { // delegated, for dynamic rows
console.log(this.id); // NB: not $(this).attr('id') !!
});
function addRow(ev) {
// unmodified
}
See http://jsfiddle.net/alnitak/aZTbA/

Categories