I am appending input fields to a div on a action. When i try to access the value inside the input field using $(this).val() i am just getting empty values.
$('#div').append('<td class = "fund-amount"><input type="number" class="custom-amount" id='+value.response_code+' placeholder="Rs."></td>');
Depending upon the action there can be any number of input field appended to the div. I want to get the values entered on each field. when i tried to to get the value using this approach below, it didn't work out. But when i got the dynamically created id value and used in the place of $(this) it worked
$(document).keyup('.custom-amount',function(){
console.log($(this).val()); //just logging empty
console.log($(this).attr('id')); //Logged undefined
})
but this one works
$(document).keyup('#100520',function(){
console.log($('#100520').val());//works
console.log($('#100520').val());//works
});
Is there anything wrong with my approach ?
$(document).on('key-up','.custom-amount',function(){
console.log($(this).val()); //just logging empty
console.log($(this).attr('id')); //Logged undefined
})
Have you tried this?
$(document).on('keyup', '.custom-amount', function(){
console.log($(this).val());
console.log($(this).attr('id'))
});
Try the following code
$('#div').append('<td class = "fund-amount"><input type="number" class="custom-amount" id='+100520+' placeholder="Rs."></td>');
$('.custom-amount').keyup(function() {
console.log($(this).val()); // value
console.log($(this).attr('id')); // id
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id= "div">
</div>
Here is the working jsfiddle:https://jsfiddle.net/cm4rLvq1/
Calling $(this) in your handler is working as expected. Because you are handling events like this $(document).keyup your handler is invoked on the document element and not on the element itself, and therefor this refers to the document.
But when you supply event arg object to your handler function, you can use its property target which will refer to the element which triggered the event, like this:
$(function() {
$(document).on("keyup", ".custom-amount",function(e){
console.log($(e.target).val());
console.log($(e.target).attr('id'));
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="custom-amount" id="some-id" />
Related
I have 'chain' of checkboxes (parent checkbox and childs), and problem is:
When first clicking on 'parent' checkbox it is working well, but after that when clicking on 'childs', the 'parent' checkbox then isn't doing what is supposed. Parent is checking/unchecking childs except the child which was pressed before.
Here is code:
JavaScript
checks_bind();
function checks_bind(){
$("#x_main").off('click');
$("#x_main").on('click',function(){
var obj = $(this);
var val = obj.is(':checked');
$("#checks").find("input[type='checkbox']").attr('checked',val);
});
}
HTML
<input id='x_main' type='checkbox'/>Main<br>
<p>--------------------------------</p>
<div id='checks'>
<input type='checkbox'/>1<br>
<input type='checkbox'/>2<br>
</div>
<p>--------------------------------</p>
<i>1 - Click on 1 or 2 <br>2 - Try <b>Main</b> checkbox. <br>
3 - Main checkbox isn't working</i>
jsfiddle example
And one more question:
Is it good to use .on('click.namespace') on checkboxes since it's working well? I can use .change() method, but I want to call .off('click.namespace') (or something to unbind) before .on() each time when calling the function.
As checked is a property, You need to use .prop() instead of .attr()
$("#checks").find("input[type='checkbox']").prop('checked', val);
Updated Fiddle, A good read .prop() vs .attr()
If you want to use .off() then its advisable to use namespaced event.
Try this: user 'prop' instead of attribute and you can check all or uncheck all as per checked condition of main check box.
Also, you can check the count of all checkbox to check /uncheck main checkbox. see below
Note: bind click handler when DOM is ready hence user $(document).ready or $(function(){})
$(function(){
$("#x_main").on("change", function(){
$("#checks").find("input[type='checkbox']").prop("checked",$(this).is(":checked"));
});
$("#checks input[type='checkbox']").on("change", function(){
var total = $("#checks").find("input[type='checkbox']").length;
var checked = $("#checks").find("input[type='checkbox']:checked").length;
$("#x_main").prop("checked",total==checked);
});
});
JSFiddle Demo
Javascript:
function editQuestion() {
$("body").on("click", ".edit_question", function(event) {
$(this).closest("form").find("textarea").text("sample text");
event.preventDefault();
});
}
$(document).ready(function() {
editQuestion();
});
HTML:
<form>
<textarea>ormar</textarea>
<div class="actions">
Cancel
</div>
</form>
When firing off the function by clicking the .edit_question link, everything is working as expected the first time.
But clicking more times (after manually removing the textarea content) doesn't do anything, why is this?
.text() only changes the initial value of the textarea, since the initial value is read from the element's content (<textarea>Initial value</textarea>).
Once you modified the value, the current value is stored in the value property of the DOM element. Changing the initial value after the textarea was modified doesn't have any effect.
That's why you should use .val() intead of .text().
Updated Demo compare with Original Demo
Use .val() instead of .text() in case of inputs.
Check this,
$(document).ready(function () {
$(document).on("click", ".edit_question", function (event) {
$(this).closest("form").find("textarea").val('sample text');
event.preventDefault();
});
});
Note: The .text() method cannot be used on form inputs or scripts.
Try using the .val() method rather than .text() method for textarea
From documentation page:
The .text() method cannot be used on form inputs or scripts. To set or get the text value of input or textarea elements, use the .val() method. To get the value of a script element, use the .html() method.
link: http://api.jquery.com/text/
<input type="text" name="val1"/>
<input type="text" name="val2"/>
$('.beta-panel input').fadeOut(function(){
$(this).remove();
$('.beta-panel').append('<h1>Done</h1>');
});
I have the above code where when a button is clicked it runs a fade out and then appends and fades in a done tag. The problem is, when it fades and removes the inputs, it shows the same amount of <h1> tags as the inputs.
Instead of:
$('.beta-panel').append('<h1>Done</h1>');
do:
$(this).closest('.beta-panel').append('<h1>Done</h1>');
$(this) holds reference to the clicked element and .closest will find the .beta-panel which is closest to $(this) and then it appends.
Try something like :
$('.beta-panel input').fadeOut(function(){
$(this).remove();
}).parent().append('<h1>Done</h1>');
You can use a .promise() in this case:
$('.beta-panel input').fadeOut(function(){
$(this).remove();
}).promise().done(function(){
$('.beta-panel').append('<h1>Done</h1>');
});
From the documentation:
.promise()
Description: Return a Promise object to observe when all actions of a
certain type bound to the collection, queued or not, have finished.
I have some search results that I'm outputting that are of this form:
<div id="result" title="nCgQDjiotG0"><img src="http://i.ytimg.com/vi/nCgQDjiotG0/default.jpg"></div>
There is one of these for each result. I'm trying to detect which one is clicked and then do some stuff. Each result has a unique title, but the same id. How do I use .click() to know which one was clicked so I can get it's ID and use it?
Here's how I'm getting the HTML from above:
$.each(response.data.items, function(i,data)
{
var video_id=data.id;
var video_title=data.title;
var video_thumb=data.thumbnail.sqDefault;
var search_results="<div id='result' title='"+video_id+"'><img src='"+video_thumb+"'></div>";
$("#searchresults").append($(search_results));
I tried
$('div').click(function(){
alert(this.id);
});
and the alert says "searchresults" (no quotes).
Additionally, this is the perfect opportunity to make use of event delegation. With this technique, you do not have to worry about re-binding click handlers after programmatic insertion of new DOM elements. You just have one handler (delegated) to a container element.
$("#searchresults").delegate("div", "click", function() {
console.log(this.id);
});
See .delegate
You can't have the same ID on multiple tags. You will have to fix that. You can use the same class, but there can only be one object in the page with a given ID value.
this.id will fetch the id value of the item clicked on and this should work fine once you get rid of conflicting IDs:
$('div').click(function(){
alert(this.id);
});
This code should be something this:
var search_results="<div id='result'" + video_id + " title='"+video_id+"'><img src='"+video_thumb+"'></div>";
$("#searchresults").append(search_results);
to coin a unique id value for each incarnation and append will just take the string - you don't need to turn it into a jQuery object.
you could get the title using $(this).attr("title").val()
I'm not sure if I have the syntax correct in the code below, I'm trying to append a var to a string parameter within the find function. I'm trying to search for a unique id within each input element of a particular form.
//Get value attribute from submit button
var name = $('#myForm').find('input#submitThis').val();
//Other code that manipulates the name variable
//Submit button in hidden form
$('.submitLink').click(function(){
$('#myForm').find('input#'+name).click();
return false;
});
The element with a submitLink class is supposed to be tied to the submit button in the form. I don't think I have the syntax correct though, when I go back and click the element that has the submitLink class, nothing happens.
The syntax appears fine to me. To be sure the selector is what you are expecting it to be, you could do something like this:
$('.submitLink').click(function() {
var selector = 'input#' + name;
alert(selector);
/* rest of the code */
});
Try adding an alert to test the var inside the event handler (and to see that the handler is fired). Also, if you are looking for an element with a specific id you don't need to include the element type. Like this:
$('.submitLink').click(function (event) {
event.preventDefault();
alert(name);
$('#' + name, $('#myForm')).click();
});
NOTE: If you are trying to find an element by its name rather than ID you must use $("input[name='foo']").