how to get the value from button on click - javascript

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);
});

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.

Jquery appending with styling and functions

i appending buttons with some IDs and i use those IDs to make on click stuff
when it appending didn't take button() effect
and on click it don't take the function that I created it for this button id
$("button#edit-doc").each(function() {
$(this).button();
$(this).on("click", function(){
alert("clicked");
});
});
append button
$("#append").on("click", function(){
$('div#container').append("<button id='edit-doc'> Edit </button>");
});
container
<div id="container"></div>
This seems to be what you're after:
function handler() { alert('clicked'); }
$("#append").on("click", appendButton);
function appendButton(){
$('#container').append(function() {
return $("<button id='edit-doc'> Edit </button>").on("click", handler);
})
}
http://jsfiddle.net/PF8xY/
See jQuery how to bind onclick event to dynamically added HTML element for more information on this behavior.
$(document).on("click", "#selector", function(){
//Your code here.
});
Using document for your selector with .on will allow you to bind events to dynamically created elements. This is the only way I've found to do it when the DOM elements don't exist prior to execution.
I do this in a dynamically created table that is sort-able and works great.
EDIT:
Here is an example. Click the button to add a div then click the div to get it's contents.
http://jsfiddle.net/FEzcC/1/
The first code-block attaches an event listner to all buttons with class='edit-doc', use classes instead of an id since an id's name may only exist once per page. So I was saying, when your browser reaches this code an event listner is added to all available buttons in your document at that moment. It doesn't add an event listner to buttons you will be adding later onclick of some element, because it doesn't know. You will have to explicitly execute the code again for the buttons that you append. But what you don't want is to add a new event listner to the original buttons, causing two events being called.
Something like:
// Load all buttons with class=edit-doc and add event listner
$(function() {
$("button.edit-doc").button().on("click", function(){
alert("clicked");
});
});
// Append button if button with id=append is clicked
$("#append").on("click", function(){
var button = $.parseHTML("<button class='edit-doc'>Edit</button>");
$('div#container').append(button);
$(button).button().on("click", function(){
alert("clicked");
});
});
Working example:
http://jsfiddle.net/RC9Vg/

Can't detect changed id

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.

remove closest input

Ok, i have input object, when it is changed it adds another one..
also there is delete (izdzēst) link when you click on, it should remove last input field..
how to that? (the function for delete is dzest )
I guess the problem is in $(this)?
<input name="userfile[]" type="file" size=40 />
Izdzēst<br />
<script>
function dzest(){
$(this).closest('input').remove();
}
$("input[type=file]").change(function() {
$('<input name="userfile[]" type="file" />').appendTo('body');
$('Izdzēst<br/>').appendTo('body');
$('.link').css('display','inline');
});
</script>
this in your code refers to the window object and not the anchor.
closest means the closest element parent, input can never be a parent, so you probably meant prev()
Fixed Code
$('Izdzēst<br/>').appendTo('body');
<a href="#" onclick="dzest(this);return false"
And the function:
function dzest(obj){
$(obj).prev('input').remove();
}
You can also use unobtrusive event handlers & delegate events.
$('body').on('click', '.link', function(){
$(this).prev('input').remove();
});
Try doing it like this instead and lose the onclick attribute.
$('a[name=dzest]').on('click', function() {
$(this).closest('input').remove();
});
Or add an ID to the delete to simplify the selector.

why jquery detach element will cause a form to submit?

i wonder why in the following example, trying to detach an element (li) causes the form containing it to submit
html
<form id="frmToDo" name="frmToDo">
<p id="lineInput">
...
<input type="submit" id="btnSubmit" value="Add" />
</p>
<ul id="todolist">
<!-- added in ajax -->
</ul>
</form>
JS
$("#frmToDo").submit(function() {
// this runs after: $("#todolist").detach(...)
});
$("#todolist").delegate("li[id^=task-] button", "click", function() {
$("#todolist").detach($($(this).parent()).id());
return false;
});
I guess you just want to remove the li element in which the button was clicked.
So instead of using
$("#todolist").delegate("li[id^=task-] button", "click", function() {
$("#todolist").detach($($(this).parent()).id());
return false;
});
Try using
$("#todolist").delegate("li[id^=task-] button", "click", function() {
$(this).parent().detach();
return false;
});
That's not a button, it's an input element.
$("#todolist").delegate("li[id^=task-] input:submit", "click", function() {
I am not sure if this is the cause of your problem but you are not using the detach function correctly if your intention is to detach an li element. The argument of the detach function is a selector expression that filters the set of matched element in the jQuery element that you are calling the function on. In your code you call detach on $('#todolist'), which means you want to detach the todolist element, if it matches the argument passed.
You should do something like this instead :
$('#todolist li').detach(); //this will detach all the li elements
I am not sure if this can explain the fact that your form is submitting. If it is not : what event triggers the submit event of your form ? Maybe you use a button or input element that is placed inside the form and triggers the submit of the form ?
Unless there's some relevant code missing, you seem to assign a handler to the onclick event outside a $(document).ready() block. That makes it possible to run the assignment before the #todolist is loaded, thus failing to find the buttons and attach handlers.
With no event cancelling, the default behaviur for a button is to submit the form.
Try this:
$(document).ready(function(){
$("#frmToDo").submit(function() {
// this runs after: $("#todolist").detach(...)
});
$("#todolist").delegate("li[id^=task-] button", "click", function() {
$("#todolist").detach($($(this).parent()).id());
return false;
});
});

Categories

Resources