Issue on Selecting Inputs inside a Div - javascript

Can you please take a look at following code and let me know why i am not able to get the ID of selected radios by using the this.id?
<div id="pay" class="btn-group" data-toggle="buttons">
<label class="btn btn-primary">
<input type="radio" name="mode" id="option1"> Cash
</label>
<label class="btn btn-primary">
<input type="radio" name="mode" id="option2"> Cheque
</label>
</div>
<script>
$("#pay input:radio").on('click',function(){
alert(this.id);
});
</script>
Thanks

If that posted code is, in fact, the entirety of your jQuery you've simply forgotten to use the document ready handler:
$(document).ready(function(){
// your code should be in here
});
Or you could ensure that your <script> is placed before the closing </body> tag, both of which approaches ensure the content of the page is loaded and present in the page before you try binding event-handlers.

Try to use
$(this).attr("id") instead of this.id

this will work;
$(function(){
$(document).on('click', '#pay input:radio', function(){
alert($(this).prop('id'))
});
})

Make sure your jQuery code is executed once the DOM is ready:
$(document).ready(function () {
// All your function calls, self-invoked functions, etc
// Also you define your event handlers here
});
From the docs about the .ready( handler ):
Specify a function to execute when the DOM is fully
loaded
Then you need to transform this into a jQuery object to access its methods, e.g. .attr() like so: $(this)
Since jQuery version 1.7 you may use event delegation by using the .on() function.
Again the docs:
Attach an event handler function for one or more events to the
selected elements.
<script>
$(document).ready(function () {
$(document).on('click', '#pay input:radio', function() {
// Instead of using alert(), use the console for debugging
window.console.log($(this).attr('id'));
});
});
</script>

Related

when jquery .html() is used to set inner HTML, .click() event on form button no longer works

I have a html form which contains a button. This button has a .click() event attached within a js file. This was working fine, until I used jquery .html() to substitute my main page content with the form content. The form shows on the page but clicking the button no longer triggers the event. I am wondering why this is? Code below...
html:
<body>
<div id="mainContent">
<!-- Visible page content will show here -->
</div>
<div id="otherScreens">
<form id="loginForm">
<label for="email">Email</label>
<input type="text" id="email" spellcheck="false">
<label for="password">Password</label>
<input type="password" id="password">
<button type="submit" id="signInBtn">Sign In</button>
<ul id="signInMessages"></ul>
</form>
</div>
css:
#otherScreens {
display: none;
}
js:
const mainContentArea = $(document).find('#mainContent');
let onPageContent = $(document).find('#loginForm').html();
$(document).ready(function () {
mainContentArea.html(onPageContent);
});
$('#signInBtn').click(function (event) {
event.preventDefault();
console.log("Hello world!");
}
I tested changing the .click() event to target #mainContent and it triggered upon clicking anywhere within the div on the webpage, as expected. So I'm not quite sure what's happening with the form button?
(does not seem to relate to suggested duplicate Q)
Just put your click function in document.ready(function()
Please check below full jQuery code and replace it with your current code:
const mainContentArea = $(document).find('#mainContent');
let onPageContent = $(document).find('#loginForm').html();
$(document).ready(function () {
mainContentArea.html(onPageContent);
$('#signInBtn').click(function (event) {
event.preventDefault();
console.log("Hello world!");
});
});
Thanks.
This is quite logical (and can be explained). You create an object, wire events to that object - then replace that object with a similar object and you expect the events to magically be wired.. That doesn't happen.
Each time you dynamically add (delete, replace, whatever) elements with events bound to that element, you need the DOM to be aware of that event. Even so, you could even end-up having more than one event wired to the same element.
So let's say (as an example).
function replaceElement(htmlContent) {
$('.mybutton').off('click'); // drop the event handler
$('#mainContent').html(htmlContent); // replace content
// add event handler
$('.mybutton').click(function() {
console.log('yup, working again');
});
}

Alternative way to use $(element).on('change', () => {})

I have a problem I hope you can help me:
I'm using bootstrap selectpicker which use the onchange event of the element (I think)
I need to add another event handler to the select element, I did and both works right, the problem is that with every certain changes in my page the table that I use reloads all the data and when that happens the table will add that event handler again to the select element and will do the same thing twice (or more)
So, before assignment of the event I tried to use
$('.selectpicker.call').off('change')
But when I do that I remove the event handler of the bootstrap selectpicker too
Do you guys know any other trick that I could use instead of jquery onchange?
Thank you!
You can use namespaces for the events this way you can distinguish just the events you've added as opposed to other events.
Let's take a very simple example - there is a button with some default functionality (Click me) and we can add more event handlers to it. We also want to clear the event handlers but not break the default functionality:
//assume some code outside our control
$("#clickme").on("click", () => console.log("Default functionality"));
//our code
$("#set_message").on("click", () =>{
const message = $("#message").val();
$("#clickme").on("click", () => console.log(message));
});
$("#clear_message").on("click", () =>{
$("#clickme").off("click");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<input id="message" value="add your message here">
<button id="set_message">Set message</button>
<button id="clear_message">Clear message</button>
</div>
<div>
<button id="clickme">Click me</button>
</div>
This doesn't work because the "Clear message" button removes all event handlers - those added by others or not.
Instead, we can namespace events. For example click.myEvent is still a click event but within the myEvent namespace. If we remove click.myEvent it only removes events from that namespace leaving anything else intact. So "Clear message" now only clears our event handlers:
//assume some code outside our control
$("#clickme").on("click", () => console.log("Default functionality"));
//our code
$("#set_message").on("click.myEvent", () =>{
const message = $("#message").val();
$("#clickme").on("click.myEvent", () => console.log(message));
});
$("#clear_message").on("click.myEvent", () =>{
$("#clickme").off("click.myEvent");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<input id="message" value="add your message here">
<button id="set_message">Set message</button>
<button id="clear_message">Clear message</button>
</div>
<div>
<button id="clickme">Click me</button>
</div>
Change this $('.selectpicker.call').on('change',function(){....}) to $('body').on('change'','.selectpicker.call',function(){....}) and load this function only once.
What this does is it assigns the function to body and triggers whenever a change event is triggered on .selectpicker.call element. So even if your data keeps changing, this function doesn't.

How to add onclick to an element using Javascript

I have an HTML button like so:
<div class="row text-center">
<button id="button1" type="submit" class="btn btn-primary">Submit</button>
</div>
I'd like to add an onclick behavior for it via Javascript. It should call another function. I have tried this:
$("#button1").addEventListener("click", showAlert());
However, the browser is complaining that $(...).addEventListener is not a function. What should I do instead?
With jQuery you can use .on():
$("#button1").on("click", showAlert);
or
$("#button1").click(showAlert);
addEventListener is a plain JavaScript method and you're trying to use it on a jQuery object. You could dereference the jQuery object using .get(0) and use it like:
$("#button1").get(0).addEventListener("click", showAlert);
or
$("#button1")[0].addEventListener("click", showAlert);
but there's really no reason.
try jquery function:
$("#button1").click(function() {
.. whatever you want to do on click, goes here...
}) ;
You could try the following:
$( "#button1" ).bind( "click", showAlert);

JQuery Slide function is n't behaving at all for data from DB

I have a database with two tables, each has three rows and both are connected by id. i executed them in .php so that each row in table_1(question) has its replies in table_2(answers).
Ans now i tried to put a SLIDEUP/SLIDEDOWN function for the answers triggered by buttons.
But unfortunately something is missing...
My Code as follows::
<div id="a" name="a">
<small><p><?php echo $row2["date"]; ?></p></small>
<p><B><big><font color= #ba4a00> A:</font></B></big> <small><?php echo $row2["answer"]; ?></small></br></p>
</div>
<button class="btn1">Slide up</button>
<button class="btn2">Slide down</button>
<script type='text/javascript'>
src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js">
</script>
<script>
$(document).ready(function(){
$(".btn2").click(function(e){
e.preventDefault();
$('[name="a"]').slideDown();
$(this).parent().$('[name="a"]').slideDown();
$(this).hide();
});
$(".btn1").click(function(e){
e.preventDefault();
$(this).parent().$('[name="a"]').slideUp();
$(this).hide();
});
});
</script>
If you open your web console, you'll see an error there about trying to call undefined as a function, because of this:
$(this).parent().$('[name="a"]').slideDown();
$(this).parent() returns a jQuery object. jQuery objects don't have a $ property.
You probably meant
$(this).parent().find('[name="a"]').slideDown();
Side note: From the code, it seems likely to me that this structure containing the div and buttons is repeated more than once on the page. If so, you need to remove the id="a" on the div, as you cannot have the same ID on more than one element.
The jQuery functions usually return a jQuery object so you can easily chain the actions. In your code you call$(this).parent().$('[name="a"]').slideDown() which is actually a kind of nonsence. The $('[name="a"=') does not belong there.
I'd suppose you want to call the $('[name="a"]').slideDown() part to slid the contents of the div down. If you want to do this, then the call to the parent() function seems to be unnecessary.

Javascript / JQuery DOM Update [duplicate]

This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
Closed 6 years ago.
I'm trying to create a form that allows user to edit the input through new window. PHP will process the input then append the new input with the new values. Apparently, when I try to edit the appended input, the JavaScript just won't fire. Please enlighten me on what I did wrong.
This is my html code:
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('.races').click(function(e){
console.log("Inside Testing");
e.preventDefault();
var currID = this.id;
var content = '<form id="theForm" action="ct.php" method="post"> Race: <input type="text" id="race" name="race"><button type="submit" onClick="OKClicked()">Click this!</button></form>';
childWin = window.open('', "_blank", "height=400, width=550, status=yes, toolbar=no, menubar=no, location=no,addressbar=no");
toBeAdded = $(this).closest('div');
childWin.document.close();
childWin.document.write(content);
popupRace = childWin.document.getElementById("race");
parentRace = document.getElementById(currID);
transferValues();
})
});
function transferValues()
{
popupRace.value = parentRace.value;
}
function setValue(text)
{
childWin.close();
toBeAdded.parent().append(text);
toBeAdded.remove();
}
</script>
</head>
<body>
<div>
Name: <input type="text" name="name">
</div>
<div>
<div>
<input type="hidden" name="race-0" value="Human" id="race-0">
<span>race: Human</span>
Edit
</div>
</div>
<div>
Name: <input type="text" name="name">
</div>
<div>
<div>
<input type="hidden" name="race-1" value="God" id="race-1">
<span>race: God</span>
Edit
</div>
</div>
</body>
</html>
And this is my php code:
<?php
$postDataKey = array_keys($_POST);
$text = "";
foreach ( $postDataKey as $currPostKey )
{
$currValue = $_POST[$currPostKey];
$text .= '<div><input type="hidden" name="'.$currPostKey.'-1" value="'.$currValue.'" id="'.$currPostKey.'-1"><span>'.$currPostKey.': '.$currValue.'</span> Edit</div>';
}
echo
'
<html>
<head>
<script>
window.opener.setValue(\''.$text.'\');
</script>
</head>
</html>
'
;
?>
jQuery is only aware of the elements in the page at the time that it runs, so new elements added to the DOM are unrecognized by jQuery. To combat that use event delegation, bubbling events from newly added items up to a point in the DOM that was there when jQuery ran on page load. Many people use document as the place to catch the bubbled event, but it isn't necessary to go that high up the DOM tree. Ideally you should delegate to the nearest parent that exists at the time of page load.
You will likely want to change event handlers so they use the on() method.
This was solved in older versions of jQuery with the live function, opposed to the bindfunction.
The bind function attached an event to all the matching elements, as long as they existed in the moment of execution. Any element appended afterwards would be excluded.
The livefunciton would attach the event on any matching element, even if the element was created after the execution of the instruction.
On the present version of jQuery, bind and live has been replaced by on. The default behavior of on()is like bind. Fortunately there is a way to use on so that it works like live.
I wrote an article about it, which it may help you understand how.
To sum it up...
// This behaves like `bind`
$(".clickable").on("click", function(){...});
// This behaves like `live`
$(".parent-element").on("click", ".clickable", function(){...});
So just search the common parent element that all possible elements could possibly have (you could use $(document) if you do not want to think too hard) and you are golden.
jQuery on Method is what you're looking for; click the link and look for delegated events.
"Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time. "

Categories