Document not detecting input value - javascript

I've had this problem for awhile now and I can't seem to fix it no matter what I do.
Basically, my input is not retrieving the value that the user types in the input for some reason..
Here is my code:
$('#aid').one('click', function () {
$('.prompt').prepend('<tr class="task"><td class="cell-icon"></td>' +
'<td class="cell-title"><div>User\'s Object: <input id="inputObject" type="text" style="margin-top: 2px;margin-left:2px"></input> Amount: <input id="inputAmount"' +
'type="text" style="margin-top:2px;margin-left:2px; padding-right: 0px"></input></div></td>' +
'<td class="cell-status hidden-phone hidden-tablet"><a class="btn btn-success" style="margin-top:3px">Submit</a></td>' +
'<td class="cell-time align-right">Just Now</td></div>' +
'</tr>');
});
$('.btn').click(function () {
console.log("click");
var input = document.getElementById('inputObject').value;
console.log(input);
});
Everything works fine including both clicks, but for some reason it just won't display the input value to the console.
I've also tried: $('#inputObject').val(); but that didn't work either.
I really hope that someone can help me here!

Another method: use delegate.
$('body').delegate('.btn', "click", function() {
var inp = document.getElementById("inputObject").value;
console.log(inp);
});
Explanation from http://www.w3schools.com/jquery/event_delegate.asp:
The delegate() method attaches one or more event handlers for specified elements that are children of selected elements, and specifies a function to run when the events occur.
Event handlers attached using the delegate() method will work for both current and FUTURE elements (like a new element created by a script).

You are creating your HTML code dynamically so try using:
$(document).on("click",".btn", function(){
do stuff here...
});

Related

Button does not call function when clicked

I'd like a function t run when a button is clicked. It works fine when I approach it like so in the html body
<div type="button" id="decline" class="btn btn-danger mrs"></div>
However, I need it to work within the below code block, which is within a underscore.js wrapper. At the moment the function won't execute using the below, I'd like to understand why? is the id in the wrong place?
$('#containerFriendsPending').empty();
_.each(friends, function(item) {
var wrapper = $('<div class="portfolio-item-thumb one-third"></div>');
wrapper.append('<div type="button"
id="decline"
class="btn btn-danger mrs">' +
'Decline' +
'</div>');
$('#containerFriendsPending').append(wrapper);
});
While the code solution you posted will work the first time:
$('#decline').click(function() {
Friendrequest_decline();
});
It will not work after the wrapper code is replaced, as per your answer. You must use .on() to delegate the event:
$(document).on('click', '#decline', function() {
Friendrequest_decline();
});
or
$('#containerFriendsPending').on('click', '#decline', function() {
Friendrequest_decline();
});
Eg:
$(document).on('click', '#id', function() {}) vs $('#id').on('click', function(){})
Solved this myself.
The following needed to be added within the original question main code block
$('.decline').click(function() {
Friendrequest_decline();
});
So doing this works.
$('#containerFriendsPending').empty();
_.each(friends, function(item) {
var wrapper = $('<div class="portfolio-item-thumb one-third"></div>');
wrapper.append('<div type="button" id="decline" class="btn btn-danger mrs">' + 'Decline' + '</div>');
$('#containerFriendsPending').append(wrapper);
$('.decline').click(function() {
Friendrequest_decline();
});
});
As you didn't provide the code that launches the click event it's hard to debug, but I'm going to assume it's actually the most common mistake that causes this problem: You are binding the click event before the element actually exists. That way, the browser will not know the new element also needs the click event.
Example:
$('.test').click(someFunction);
$('body').append( $('<div class="test">Click me!</div>');
This will not work, because the click event is bound first and the element is created later.
The jQuery .on() function can handle that by also watching for new elements that are created in the DOM:
$('body').on('click', '.test', someFunction);
$('body').append( $('<div class="test">Click me!</div>');
Now it will run someFunction successfully.

Find Id of clicked button

I wanted to get the id of clicked button since i have 4-5 buttons on my form.
<button type="submit" style="height: 30px" id="btnHelp" name="btnHelp" onclick="ShowHelp(2);return false;">Help</button>
<button type="button" style="height: 30px" id="btnClose" name="btnClose" onclick="Close();return false;">Close</button>
<button type="button" style="height: 30px" id="btnSave" name="btnSave" onclick="Save();return false;">Close</button>
...............................
Whichever may be the button click, I just want to get id of that button.
$(function () {
var id = $(this).attr('id');
alert(id);
})
Also with
$("input").click(function (event) {
var urlid = $(this).attr('id')
alert(urlid);
})
but i am getting the alert as undefined.
How can i get id of button clicked?
Please help me.
Try
:button Selector
Selects all button elements and elements of type button.
$(":button").click(function (event) {
var urlid = this.id;
alert(urlid);
});
Fiddle Demo
Problem
$("input") --> selects elements with tag input eg. <input type="text"/> but not <button> tag .
I'd try to replace this with the event triggerer.
var urlid = $(event.target).attr("id");
Also, probably your onclick function is preventing your script to be executed, because it's handling the click event, not letting your function do it.
I ditched the onclick attributes of buttons you have, and hooked click events to button rather than input, and it worked. So check whether you are connecting to the right element.
See example here.
<script>
jQuery(":button").click(function (event) {
var urlid = $(this).attr('id')
alert(urlid);
})
</script>
Try this its work
very simply:
$("input").click(function (event) {
var urlid = this.id;
alert(urlid);
})
for button:
$("button").click(function (event) {
var urlid = this.id;
alert(urlid);
})
You might try use event passed as argument into any event handler instead of this for event.target is referring to element actually triggering your handler (being clicked) and event.delegateTarget being element handler has been attached to initially. In both cases you might have to use $() for using jQuery or simply stick with accessing .id in either case.
In your case this would be
$("input").click(function (event) {
var urlid = $(event.delegateTarget).attr('id');
alert(urlid);
});
to ensure handler is always accessing that it has been attached to, here.
Except for this quite simple scenario relying on this is sometimes trickier than using provided arguments.
EDIT : However, your case seems to be related to issues encountered by Tusha Gupta, for sure. Your buttons aren't "inputs" so that handlers are never attached, actually.
$(function () {
$("button").click(function () {
alert($(this).attr("id"));
});
});

Using an undeclared attribute for jquery event

This code is used to pop up a set of checkboxes that is generated when the radiobox with the value of Up is selected.
// Experiment
$("input[name='production-level']").on('change', function() {
var production = $(this).val();
var result = '';
if(production == 'Up') {
result = '<p class="question">Reasons why it is '+ production +'. Click as many as apply.</p>'
+ '<input type="checkbox" name="production-rsn[]" value="Increase in demand" required>Increase in demand <br/>'
+ '<input type="checkbox" name="production-rsn[]" value="Expected increase in demand">Expected increase in demand <br/>'
+ '<input type="checkbox" name="production-rsn[]" value="Fullfillment of past orders">Fulfillment of past orders <br/>'
+ '<input type="checkbox" name="production-rsn[]" value="Increased marketing activity">Increased marketing activity <br/>'
+ '<input type="checkbox" name="production-rsn[]" value="other" />Other';
}
$('#production').html(result);
});
And this code is used to pop up a textbox when the checkbox included in the generated code by the above function with value="other" is checked/ticked. The problem is it won't append!
$("input[name='production-rsn[]']").on('change', function () {
var result = '';
//check if the selected option is others
if (this.value === "other") {
result = '<input id="productionOther" maxlength="30" minlength="3" name="production-other" type="text"/>';
}
$('#production').append(result);
});
The problem is the textbox won't append! Any ideas?
As you are creating elements dynamically you need to use Event Delegation. You have to use .on() using delegated-events approach.
i.e.
$(document).on(event, selector, callback_function)
Example
$('#production').on('change', "input[name='production-rsn[]']", function(){
//Your code
});
In place of document you should use closest static container. In your case its '#production'
The delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time. By picking an element that is guaranteed to be present at the time the delegated event handler is attached, we can use delegated events to bind the click event to dynamically created elements and also to avoid the need to frequently attach and remove event handlers.
Since your input elements have been added dynamically to the DOM, all the events will not be available for these newly created input until you attach those events to them, you can achieve it using event delegation:
Event delegation allows us to attach a single event listener, to a
parent element, that will fire for all children matching a selector,
whether those children exist now or are added in the future.
$('#production').on('change', "input[name='production-rsn[]']", function () {
var result = '';
//check if the selected option is others
if (this.value === "other") {
result = '<input id="productionOther" maxlength="30" minlength="3" name="production-other" type="text"/>';
}
$('#production').append(result);
});

jquery class selector only registering events on first element of class

im currently working on a form field highlighter in jquery and so far it works except it only works on the first line of the form and the rest of the fields do not register my focus events so that i may apply focus formatting
i am currently using the following jquery code
var debug = false;
$(function(){
$(".email-form tbody:last").AddFormLineToTable();
$("#do-add-row").click(function () {
if(debug)
{
alert("serialize click eventhandler fired");
}
$(".email-form tbody:last").AddFormLineToTable();
});
$(".does-focus-highlight").focusin(function(e){
$(e.target).addClass("focus-highlight");
if(debug){alert('field did focus');}
});
$(".does-focus-highlight").focusout(function(e){
$(e.target).removeClass("focus-highlight");
if(debug){alert('field did blur');}
});
$("#do-serialize").click(function(){
if(debug)
{
alert("serialize click eventhandler fired");
}
var jsn = $("#contact-form").serializeArray();
$("#serialize-target").val(JSON.stringify(jsn,null,2));
});
});
is there something im missing to catch these additional events
the form fields that are not firing are being generated dunamically as well if that makes a difference as well
which are being generated as follows
var lineCount = 0;
jQuery.fn.AddFormLineToTable = function() {
var o = $(this[0]);
o.append('<tr id="contact-'+lineCount+'">' +
'<td>Name: <input class="does-focus-highlight" id="contact-name-'+lineCount+'" name="contact-name-'+lineCount+'" type="text" required="required" /></td>' +
'<td>Email: <input class="does-focus-highlight" id="contact-email-'+lineCount+'" name="contact-email-'+lineCount+'" type="email" required="required" /></td>' +
'</tr>');
lineCount++;
};
.click() binds events only to elements that are existing at the time of calling .click(). If you want the events to be handled for elements that are created later on, use .on() or .live(), depending on the version of jQuery you are using. Read the very helpful info here.

replacing element with jQuery

I have <form>s on my page that I want to replace with <button>s. The thing that is causing me difficulty is that I want to use the value of the <form>'s submit input as the html for the button.
<form action="/postcomment/" method="post">
<inputs>
.
.
.
<input type="submit" value="Reply">
</form>
Becomes
<button class="postcomment">Reply</button>
I'm having a hard time wrapping my mind around the chaining here. I need to grab the data values (e.g. "Reply") and then insert them into the button elements in one jQuery operation (or else manage the ordering with something like .index()) and I haven't figure out how to do that yet.
Working example here: http://jsfiddle.net/Mch86/
$(document).ready(function(){
$('form').each(function(){
button = $('<button>' + $('input[type="submit"]', this).val() + '</button>').addClass($(this).attr('action').replace(/\//g, ''));
$(this).replaceWith(button);
});
});
Do something like this:
$('input[type="submit"]').replaceWith(function () {
return $('<button>').text(this.value).addClass('postcomment');
});
jsFiddle Demo
This will replace all of your submit buttons (<input type="submit">) with a <button>, keeping the text on the button.
replaceWith() allows you to use a function as its parameter, which has a reference to the individual submits themselves (this).
Since you said you have multiple forms:
$(function() {
$('form').each(function() {
var str = $(this).find('input[type="submit"]').val();
$(this).replaceWith($('<button/>').addClass("postcomment").text(str));
});
});
You could do:
var label = $('form input:submit').val();
var action = $('form').attr('action').replace(/\//g, '');
var button = $('<button />', { class: action});
button.html(label);
$('form').replaceWith(button)
;
fiddle here: http://jsfiddle.net/be3af/1/

Categories

Resources