Can't detect changed id - javascript

When I change the id of a button I cannot find the new id with on.("click"). The function console.log() does detect that it's changed but I cannot detect it with the on() function.
HTML:
<form id="formName" action="" method="post">
<input type="submit" id="submitBtn" value="Submit" />
</form>
<button id="change">Change</button>
JS:
$("#change").on("click", function(){
$("#submitBtn").attr("id", "NewBtn");
});
$("#formName").submit(function(e){
e.preventDefault();
});
$("#NewBtn").on("click", function(){
alert("Hello");
});
So I need it to alert "Hello" after I have clicked on change. It does change the id I checked that with inspect element.
Fiddle: http://jsfiddle.net/WvbXX/

Change
$("#NewBtn").on("click", function(){
to
$(document).on("click", "#NewBtn", function(){
The reason for this is that you're wanting to use the delegate form of .on(). This call is a little different in that it takes a "string" as the second parameter. That string is the selector for your "dynamic" element while the main selector need either be a parent container (not created dynamically) or the document itself.
jsFiddle

you are setting onclick event for newBtn on load of page for the first time but unfortunately newBtn not available that time. hence after changing the id it will not trigger onclick function for newBtn.
you can do one thing to make it work, set onclick event for newBtn inside the same function where you are changing the id like below.
$("#change").on("click", function(){
$("#submitBtn").attr("id", "NewBtn");
// set on click event for new button
$("#NewBtn").on("click", function(){
alert("Hello");
});
});

.attr() function does not have a callback and thus it cannot be checked unless you setup an interval using setInterval but the function itself executes pretty soon so you are not going to need it.
For solving the problem in hand event delegation proposed by tymeJV is the right way to do it.

Related

.click() not working on a specific index

I'm creating a dynamic menu where I can add and remove a new form.
<input type="button" value="generate form" id="test"/>
<div id="form1"></div>
<script>
$(document).ready(function() {
$("#test").click(function() {
$("#form1").append("<select id='score-attempt'><option value='penalty'>penalty</option></select><input type='button' value='remove' id='remove'/><br>");
});
$("#form1 #remove").click(function() {
alert($(this).index());
});
});
The problem is that clicking on remove never triggers the alert box.
Thanks
The problem is that the element is added later and doesn't exist when the dom is loaded. Therefore the click event has to be delegated from an already existing element, e.g. like this:
$(document).on("click", "#remove", function(){
alert($(this).index() );
});
Instead of $(document) every other static parent element can be used for event delegation, just as example.
Update for the comments: as mentioned, $(document) only as example. I'd also prefer to use $("#form1") here like mithunsatheesh suggested.
And for reference: https://api.jquery.com/on/#on-events-selector-data-handler, section "Direct and delegated events":
"Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the call to .on()."
Update for the correct index: you'll get the correct index using e.g.
$("#form1").on("click", ".remove", function(){
alert($(".remove").index($(this)));
});
with the adjustment to use remove as class instead of id for the remove-button. IDs have to be unique, so classes are a better solution. index() starts counting with 0, so you'll get 0 for the first one.
As working example: Fiddle
You need to add an event handler on your #form1 input with #remove.
Look here, here and here.
Here is the working jsfiddle for you.

How to get the value of an input button using this in jQuery

Thanks in advance for helping
Inside a function in a script, I'm trying to get the value of a button when it's clicked.
I just can't figure out the usage of "this" in that case.
There are a certain number of buttons in the page and several functions attached to them so I don't want to do jQuery('.A1').val() in the function each time a button is clicked.
I want the function to detect which button is clicked and its value
<script>
jQuery(document).ready(function(){
$.fn.dosomething = function(){
var currentval = $(this).val();
console.log(currentval);
};
});
</script>
<INPUT type="button" class="A1" value="blabla" onclick="jQuery().dosomething()"/>
The console returns 'undefined'
Thank you for your help
Dom
You need to pass current object this to the function like
<INPUT type="button"
class="A1" value="blabla"
onclick="jQuery(this).dosomething()"/>
DEMO
EDIT
Why are you using inline onclick? You can bind event to element also like
$(".A1").on("click", function () {
jQuery(this).dosomething();
})
DEMO 2
Try using the jquery click function rather than the on click inline HTML call.
http://api.jquery.com/click/
With $.fn.dosomething = function(), you have defined a plugin that can be called on a jquery object, but you pass nothing into jquery to serve as this.
Try:
onclick="jQuery(this).dosomething()"
Try this,
We can bind the function on particualr event for particular element.
jQuery(document).ready(function(){
$.fn.dosomething = function(cthis){
var currentval = $(cthis).val();
alert(currentval);
console.log(currentval);
};
$( "#myId" ).bind( "click", function() {
jQuery().dosomething(this);
})
});
</script>
<INPUT id="myId" type="button" class="A1" value="blabla" />
Demo
I think, the this inside the $.fn.dosomething refers itself rather than clicked button.

Toggle state of textbox with javascript using a button

I have a form as follows:
<form>
<label for="input">Input:</label>
<input type="text" id="input" maxlength="3"></input>
<button type="button" id="lock" onMouseDown="toggleInput()"></button>
</form>
And javascript code:
function toggleInput(){
if ($("#input").disabled){
$("#input").disabled = false;
}
else {
$("#input").disabled = true;
};
}
What I basically want to do is to check what state (enabled/disabled) the textbox is in, and then toggle the state accordingly. I don't know if the javascript portion even uses the correct syntax to check if the textbox is disabled, but it's what I could think of.
Thanks in advance!
EDIT: Reason as to why I've chosen to use onmousedown instead of onclick to execute the event with the button:
I have chosen to use onmousedown instead of onclick as it makes the app I'm building feel less clunky due to the presence of this feature with onclick: When you click on a button and then drag the cursor away from the button while holding the mouse button down, and subsequently lift your finger off the mouse button when the cursor is in an area away from the button on the webpage, the event will not be executed. Hence, I've chosen to use onmousedown as this is overcome.
Use .prop(), Get the value of a property for the first element in the set of matched elements or set one or more properties for every matched element
$("#input").prop('disabled',!$("#input").prop('disabled'))
DEMO
I am not sure why you are using onMouseDown. Use click instead
$("#lock").on("click", function() {
$("#input").prop('disabled',!$("#input").prop('disabled'))
});
DEMO with click
To do it with jQuery try this:
$("#input").prop("disabled", function(i, v) { return !v; });
Your existing code doesn't work because DOM elements have a .disabled property, but jQuery objects do not.
I'm not sure why you're using onmousedown instead of onclick for the button, but either way if you're going to use jQuery I'd recommend removing the inline event attribute in favour of binding the handler with jQuery:
$("#lock").on("click", function() {
$("#input").prop("disabled", function(i, v) { return !v; });
});
(You'd need to include that code either in a script block at the end of the body or in a document ready handler.)
Demo: http://jsfiddle.net/a7f8v/
You should append the event handler with jQuery instead of an onMouseDown event. The syntax could look like this:
<label for="input">Input:</label>
<input type="text" id="input" maxlength="3"></input>
<button type="button" id="lock"></button>
JavaScript:
$(document).ready(function() {
$("#lock").click(function() {
var input = $("#input");
input.prop('disabled',!input.is(':disabled'))
});
});
Example

how to get the value from button on click

I am having some buttons which are created dynamically based on the number of phone numbers present.Suppose I have 3 names in DB so there will be three buttons.So when I click on the 1st button then it should give the value of first button,if 2nd is clicked then 2nd button value should display.This is simple jsfiddle which describes about my requirement.I thought of assigning the each button a different id which should be the phone number.In the jsfiddle when i am clicking on a particular button then alert pops but it does not give any value.
i did like this
$('.btn').click(function(){
var number1 = $('#s2').val();
alert(number1);
});
You have to use event delegation using jQuery's on() method. From its documentation:
When a selector is provided, the event handler is referred to as delegated. The handler is not called when the event occurs directly on the bound element, but only for descendants (inner elements) that match the selector. jQuery bubbles the event from the event target up to the element where the handler is attached (i.e., innermost to outermost element) and runs the handler for any elements along that path matching the selector.
In your case, you'll need to delegate the .btn click event to an ancestor which exists prior to that element being dynamically added to the page:
$('body').on('click', '.btn', function() {
var number1 = $('#s2').val();
alert(number1);
});
The closer you get to the .btn element, the better, so unless your document's body is the nearest non-dynamic ancestor then you'll want to change this to something a bit closer.
Edit: Further question in comments:
can I get the ID of each button
To get the id of each button, simply use this.id:
$('body').on('click', '.btn', function() {
var id = this.id;
alert(id);
});
Edit 2: Further question in comments
So as I said,ID are numbers.So if i click button1 then it will print s1 in the inputfield.Can you please tell me how to do?
As your input has an id of "number", you can simply use jQuery's .val() method to set the value of the input to the id of the clicked button:
$('body').on('click', '.btn', function(){
$('#number').val(this.id);
});
Working JSFiddle demo.
$(document).on('click', '.btn', function(){
alert($(this).val());
});
Should work. The "on" is a way of working with dynamically placed elements.
Put value attribute in button input
<button type="button" class="btn" value="test2" >test</button>
<button type="button" class="btn" value="test1" id="s1">test</button>
<button type="button" class="btn" value="test" id="s2">test</button>
And then use script
$('.btn').on('click', function() {
var number = $('#s2').val();//get value
});
If you want to get the id of the clicked button you should use attr:
$('.btn').click(function(){
var number1 = $('#s2').attr('id');
alert(number1);
});

Get the element triggering an onclick event in jquery?

I have a form where i've replaced the submit button with an input (with type=button) with an onclick which calls an existing function:
<form accept-charset="UTF-8" action="/admin/message_campaigns" class="new_message_campaign" id="new_message_campaign" method="post">
<!-- some fields -->
<input onclick="confirmSubmit();" type="button" value="Send" />
</form>
In the confirmSubmit, i'd like to be able to dynamically get the form object (to submit it), instead of having to hardcode the form's id, or pass it as part of the call to confirmSubmit(). I'd have thought that i could do this by first getting the dom element that was clicked on, ie something like this:
var form = $(this).parents("form");
where $(this) is the object that called the function, ie the input with the onclick. This doesn't work though. I think it would work if i'd set it up with the .click(function(){ syntax. Can i get the element that called the function in a different way?
EDIT - got the answer from #claudio below, for clarity here's the complete function and call:
<form accept-charset="UTF-8" action="/admin/message_campaigns" class="new_message_campaign" id="new_message_campaign" method="post">
<!-- some fields -->
<input onclick="confirmSubmit($(this));" type="button" value="Send" />
</form>
and the function itself. Note that 'jConfirm' is a method of the jquery-alerts plugin (http://abeautifulsite.net/blog/2008/12/jquery-alert-dialogs/) but that's not really relevant to this question - the key thing was just to get the form object, not what's subsequently done with it:
function confirmSubmit(caller) {
var form = caller.parents("form");
jConfirm('Are you sure?', 'Please Confirm', function(result){
if (result) {
form.submit();
} else {
return false;
}
});
}
You can pass the inline handler the this keyword, obtaining the element which fired the event.
like,
onclick="confirmSubmit(this);"
If you don't want to pass the clicked on element to the function through a parameter, then you need to access the event object that is happening, and get the target from that object. This is most easily done if you bind the click event like this:
$('#sendButton').click(function(e){
var SendButton = $(e.target);
var TheForm = SendButton.parents('form');
TheForm.submit();
return false;
});
Try this
<input onclick="confirmSubmit(event);" type="button" value="Send" />
Along with this
function confirmSubmit(event){
var domElement =$(event.target);
console.log(domElement.attr('type'));
}
I tried it in firefox, it prints the 'type' attribute of dom Element clicked. I guess you can then get the form via the parents() methods using this object.
It's top google stackoverflow question, but all answers are not jQuery related!
$(".someclass").click(
function(event)
{
console.log(event, this);
}
);
'event' contains 2 important values:
event.currentTarget - element to which event is triggered ('.someclass' element)
event.target - element clicked (in case when inside '.someclass' [div] are other elements and you clicked on of them)
this - is set to triggered element ('.someclass'), but it's JavaScript element, not jQuery element, so if you want to use some jQuery function on it, you must first change it to jQuery element: $(this)
When your refresh the page and reload the scripts again; this method not work. You have to use jquery "unbind" method.
First Way: Send trigger element using this
<button id="btn01" onClick="myFun(this)">B1</button>
<button id="btn02" onClick="myFun(this)">B2</button>
<button id="btn03" onClick="myFun(this)">B3</button>
<script>
function myFun(trigger_element)
{
// Get your element:
var clicked_element = trigger_element
alert(clicked_element.id + "Was clicked!!!");
}
</script>
This way send an object of type: HTMLElement and you get the element itself. you don't need to care if the element has an id or any other property. And it works by itself just fine.
Second Way: Send trigger element id using this.id
<button id="btn01" onClick="myFun(this.id)">B1</button>
<button id="btn02" onClick="myFun(this.id)">B2</button>
<button id="btn03" onClick="myFun(this.id)">B3</button>
<script>
function myFun(clicked_id)
{
// Get your element:
var clicked_element = document.getElementById(clicked_id)
alert(clicked_id + "Was clicked!!!");
}
</script>
This way send an object of type: String and you DO NOT get the element itself. So before use, you need to make sure that your element already has an id.
You mustn't send the element id by yourself such as onClick="myFun(btn02)". it's not CLEAN CODE and it makes your code lose functionality.

Categories

Resources