After appending table I am checking on button click event. Javascript alert is working but jQuery click event is not working.
I cannot seem to find my mistake.
$("#inputcon").change(function(e){
if($(this).attr('checked')){
$(this).val('TRUE');
}else{
$(this).val('FALSE');
}
if($(this).val() == 'TRUE'){
$("div#Add").append(' <table id="inputT" style=""> <tr> ' +
'<td><label>Input Control Name :</label> </td>' +
' <td><input id="icname" type="text" name="icname" ></td>' +
' </tr>' +
' <tr>' +
' <td><label>Parameter Name :</label> </td>' +
' <td><input id="pname" type="text" name="pname" ></td>' +
' </tr> ' +
' <tr >' +
' <td><label>DataType:</label> </td>' +
' <td><select name="datatype" class="texta" id="datatype" style="width: 328px " > ' +
' <option value="string">Text</option> ' +
' <option value="date">Date</option>' +
' <option value="number">Number</option>' +
' </select></td>' +
' </tr>' +
' <tr >' +
' <td><label>Input Type:</label> </td>' +
' <td> <select name="inputtype" class="texta" id="inputtype" style="width: 328px " >' +
' <option value="text">Text</option>' +
' <option value="date">Date</option>' +
' <option value="singleList">Single Select List</option>' +
' <option value="singleQue" >Single Select Query List</option>' +
' <option value="multiList" selected="true">Multi Select List</option>' +
' <option value="multiQue" selected="true">Multi Select Query List</option>' +
' </select></td>' +
' </tr><tr><td><input onClick="alert(this.id);" id="inconbutt" type="button" value="Add InputControl" name="Add InputControl"></td></tr> </table>');
}else{
$("table#inputT").remove();
}
});
$("#inconbutt").click(function() {
alert("add");
var i1 = $("#icname").val() ;
var pname = $("#pname").val();
var dtype = $("#datatype").val();
var itype = $("#inputtype").val() ;
alert(i1);
alert(pname);
alert(dtype);
alert(itype);
/* $.ajax({
type:"POST",
url:"Welcome.jsp",
data:"inputname="+i1+"&pname="+pname+"&datatype="+dtype+"&intype"+itype,
success: function(){
$("table#inputT").remove();
$("table#tableI").append(' <tr><td>'+i1+'</td><td>Remove</td></tr> ' ) ;
}
}); */
});
The jQuery function you created with .click at bind at the start of the load and your input is being placed after that. So jQuery doesn't recognize the event and your function isn't called.
Try using dynamic binding functions such as:
$.live(/*yourevent*/'click', function(){
// your function
});
OR
$.delegate(/*selector*/, 'click', function(){
//your function
});
OR if you are using newer version of jQuery 1.7+ then you can also use
$.on('click', /*selector*/, function(){
//your function
});
You can't bind an event handler directly to an element that doesn't exist yet. But you can use a delegated event handler bound to the parent element of the element that will be created later:
$("div#Add").on("click", "#inconbutt", function() {
// your code here
});
With that syntax of .on(), jQuery will process any click within the parent "div#Add" element, and test whether it occurred on an element that matches the "#inconbutt" selector in the second parameter. If it does your function is called.
If you're using a version of jQuery older than 1.7 use .delegate() instead of .on(). If you're using a version older than 1.4.2 use .live().
Alternatively, move the $("#inconbutt").click(...) to within the if statement where you append the element.
Rather than appending and removing the whole table every time the checkbox is clicked I'd suggest including it in your code all the time but showing and hiding it.
You're trying to bind an event to the element, which does not exist yet.
Try to use $(document).on('click', '#inconbutt', function() { ... });
Use .on method of jquery
$(document).on('click', '.button.clickable', function () {...});
Related
Here is the script i'm using to append name input field-
<script>
$(document).ready(function() {
$("#add").click(function() {
var someId = document.getElementById('someId').value;
var name = document.getElementById('name').value;
$('.print_box').append('<div class="' + someId + '"> <tr> <td> <input type="button" ref="'+someId+'" class="remove_button" value="Remove"></td> <td><input type="text" multiple name="name[]" value="' + name + '" </td> </tr>
});
});
</script>
Now I want to call remove button from a separate standalone script like-
<script>
$(document).ready(function() {
$(".remove_button").click(function() {
var getRemoveID = $(this).attr('ref');
$("." + getRemoveID + "").remove();
});
});
</script>
But this isn't working. It only works when remove function is included with append like-
<script>
$(document).ready(function() {
$("#add").click(function() {
var someId = document.getElementById('someId').value;
var name = document.getElementById('name').value;
$('.print_box').append('<div class="' + someId + '"> <tr> <td> <input type="button" ref="' + someId + '" class="remove_button" value="Remove"></td> <td><input type="text" multiple name="name[]" value="' + name + '" </td> </tr>
$(".remove_button").click(function() {
var getRemoveID = $(this).attr('ref');
$("." + getRemoveID + "").remove();
});
});
});
</script>
Now, How can I seperate those 2 function? i mean calling remove button outside that append script??
Just use on
$("body").on("click", ".button", function() {
alert("click")
});
https://codepen.io/anon/pen/BxRNjM
This is not how you solve it. You are going in wrong direction. The problem here is that you are trying to handle events for the elements which are being added on the DOM dynamically.
So you need to handle events like (click, mouseover etc) for those elements in this way
$(document).on('click', '.remove_button', function(){
//Code to handle that event when click on remove_button
});
I'm creating a Jquery Mobile range dynamic with this code:
$('<input data-type="' + elementType + '" id="' + name +' " min=' + value1 +' max=' + value2 + ' value="127" >').appendTo("fieldset");
Now I want to add a change event with this code:
$(".brightness").change(function() {
alert("changed");
});
I have no idea why it's not working, I tried to refresh the range after defining the event, I tried to bind the event to the range, nothing works. The function that contains the first code snippet, is getting called first, and the function that contains the second snipped is getting called second.
Does someone of you know what I'm doing wrong, or what I'm overlooking?
Two things you need to do
1. add css class brightness to your range input
$('<input class="brightness" data-type="' + elementType + '" id="' + name +' " min=' + value1 +' max=' + value2 + ' value="127" >').appendTo("fieldset");
Add event handler using on
$(document).on("change",".brightness",function() {
alert("changed");
});
EDIT - for id selector use # instead of .(dot) like below
$(document).on("change","#brightness",function() {
alert("changed");
});
Check jQuery Selector
Use on method for your dynamically created elements
$(".brightness").on('change',function() {
alert("changed");
});
I think you are giving id brightness and Calling Onchange Event by Class using dot(.).
if the name of the id is brightness then
you should use #
$("#brightness").on('change',function() {
alert("changed");
});
but if you want call onchange event by class only then you need to add class to your input and use dot(.)
$('<input class="brightness" data-type="' + elementType + '" id="' + name +' " min=' + value1 +' max=' + value2 + ' value="127" >').appendTo("fieldset");
$(".brightness").on('change',function() {
alert("changed");
});
I have a modal dialog (Bootstrap) that has a list-group with custom list-group-items inside of it (populated by loop using append after adding data from my server).
Inside each list-group-item, I have a Checkbox that will be used to "select" the result. As I populate the items, I hook up the JQuery click event to the respective Checkbox:
// Add to search results
$('#search-results').append(
'<a id="centroid-list-item-' + featureAttrs['ObjectID'] + '" href="\\#"' + 'class="list-group-item" style="outline: 0">' +
'<table style="background: transparent">' +
'<tr>' +
'<td>' +
'<input id="centroid-checkbox-' + featureAttrs['ObjectID'] + '" type="checkbox" value=""> ' +
'</td>' +
'<td>' +
'<h4 class="list-group-item-heading">' +
featureAttrs['UNIQUEID'] +
'</h4>' +
'<p id="centroid-item-text-' + featureAttrs['ObjectID'] + '"' + 'class="list-group-item-text">' +
featureAttrs['NAME'] +
'</p>' +
'</td>' +
'</tr>' +
'</table>' +
'</a>'
);
// When the DOM is ready, add event
$(document).ready(function () {
$('#centroid-checkbox-' + featureAttrs['ObjectID']).click(function (event) {
var objectId = $(this).attr('id').replace(/^\D+/g, '');
console.log(objectId + " was clicked");
if ($(this).is(':checked')) {
// Enable the 'Set Target' button
$('#btn-set-target').removeAttr('disabled');
// Disable all other choices
$('[id^="centroid-checkbox-"]').each(function (event) {
console.log("Picked up values for checkboxes");
if ($(this).attr('id') != ('centroid-checkbox-' + objectId)) {
$(this).attr('disabled', true);
}
});
}
else {
$('#btn-set-target').attr('disabled', 'disabled');
// Enable all text boxes
$('[id^="centroid-checkbox-"]').each(function () {
if (this.attr('id') !== ('centroid-checkbox-' + objectId)) {
this.removeAttr('disabled');
}
});
}
});
});
The problem I am having is that when I call $('[id^="centroid-checkbox-"]') it is returning undefined. However, at the time is gets called, there are about 30 "centroid-checkbox-XXXXX" checkboxes. What am I doing wrong here?
The $ function never returns undefined.
But this in the callback you pass to each is an element, not a jQuery object.
Which means you must use this.id instead of this.attr('id') and $(this).removeAttr('disabled') instead of this.removeAttr('disabled') (and you probably want this.disabled=false or $(this).prop('disabled', false)).
objectId never gets defined because you need to quote enclose the regular expression you're using for replace():
var objectId = $(this).attr('id').replace(/^\D+/g, '');
should be:
var objectId = $(this).attr('id').replace('/^\D+/g', '');
DEMO: http://jsfiddle.net/4fUvn/8/
I'm beginning in JQuery, and I'd like to know if there is a way to send a selected item from a selectlist to a JQuery function.
So, here is the fiddle I've used :
http://jsfiddle.net/YCPM7/7/
I'd like to know if there is a way to replace the 'option:select' that I've set inside the call of the function.
Here is a part of the code that's on the fiddle :
<select id="StateSelection1" name="StateSelection">
<option value="1">state 1</option>
<option value="2">state 2</option>
<option value="3">state 3</option>
<option value="4">state 4</option>
<option value="5">state 5</option>
</select>
</td><td>
<input type="button" value="envoi" class="bouton" name="test" onclick="switchDiv(1, 'option:select')"/>
the '1' that you can see inside "switchDiv(1, 'option:select')" is not really important. That's an id that will be generated by razor (vb.net).
Easy do. First of all, put an ID to the button. Let's call it btnTest.
And now, to the jQuery part, use this :
$("#btnTest").click( function() {
alert($("#StateSelection1 option:selected").text());
});
This will get the Text of the select, to get the index use val() instead of text()
I've tried not to edit the HTML you've shown in your jsfiddle too much, only adding the .js-target, .js-1 and .js-2 classes to help explain what's being done.
The below bit of jQuery should hide all of the divs to begin with, and then when clicking on one of the buttons, hide them all again and just display the div whose option was selected.
$(".js-target").hide();
$(".bouton").on("click", function() {
$this = $(this);
if ($this.hasClass("js-1")) {
number = "1";
} else if ($this.hasClass("js-2")) {
number = "2";
}
target = $('#StateSelection' + number + ' option:selected').val();
$(".js-target").hide();
$("#" + number + "/" + target).show();
});
The fiddle can be viewed here.
once u get the value to select u can use
$("#btnTest").click( function() {
$("#StateSelection1").val(YOUR_VALUE);
}
Finally I choose to do this with a onClick method, which seemed to be a lot easier :
<script type="text/javascript">
function switchDiv(idCont) {
value = $('#DivSelection' + idCont + ' option:selected').val();
alert("contactid = " + idCont + " DivSelected = " + value);
$("#" + idCont + "1").hide();
$("#" + idCont + "2").hide();
$("#" + idCont + "3").hide();
$("#" + idCont + "4").hide();
$("#" + idCont + "5").hide();
$("#" + idCont + "6").hide();
$("#" + idCont + "7").hide();
$("#" + idCont + "8").hide();
$("#" + idCont + "9").hide();
$("#" + idCont + value).show();
};
</script>
<input id=#item.idContact type="button" value="Envoyer" class="bouton" onclick="switchDiv(#item.idContact)" />
If it isn't clear what I'm trying to do here, I need to select a dynamically generated class from the document and bind a click function to it. Here is the code. Selecting the variable class, if it exists is posing the problem.
if( item.current == '2' )
{
playBeep = true;
htmlStr += '<tr class="current-alert curaler' + incrementer.toString() + '">';
var selectorString = 'curaler' + incrementer.toString();
$( ('.' + selectorString) ).bind( 'click' , function()
{
alert('hi');
});
}
else if ( item.current == '1')
{
htmlStr += '<tr class="current">';
}
else
{
htmlStr += '<tr>';
}
htmlStr += ' <td class="first">' + item.percent + '%</td>';
htmlStr += ' <td class="second ' + ( ( item.current == '2' ) ? 'sym' + incrementer.toString() : '' ) + ' ">' + item.symbol + '</td>';
if(item.symbol != 'CASH'){
htmlStr += ' <td class="third">#</td>';
} else {
htmlStr += ' <td class="third"> </td>';
}
htmlStr += ' <td class="fourth">' + item.purchasedAt + '</td>';
htmlStr += ' <td class="stockName">' + item.fullName + '</td>';
htmlStr += ' </tr>';
});
htmlStr += ' </table>';
} else {
htmlStr += "<i>100% Cash</i>";
}
It doesn't work because the element you're trying to target is not part of the dom yet.
Try using live():
$('.' + selectorString).live ('click' , function() { ... } );
or, for jquery 1.7 onwards use on():
$('.' + selectorString).on('click' , function() { ... } );
Alternatively, just make sure you run bind() after the element has been inserted.
If you're generating multiple elements, it might be easier to just make sure they all have a common class and use assign your click event to that class using live() or on().
Your selector is correct as you have it, however if the element does not exist yet when this is executed, it might now be found.
Here is an alternative method which would pick up any element with a partial class match:
$("[class^='curaler']").on('click', function(){
//do stuff here
});
Done the way above, you don't have to put this in your conditional, it can just be in your
$(document).ready(function(){
// put it here
}};
EDIT: Based o your last update:
$( ('.' + selectorString) ).
should be
$('.' + selectorString).
or
var myselector= '.' + selectorString;
$(myselector).on('click',function(){
alert( $(this).text());//sample to alert the text of the clicked element
});
NOTE: If you are using pre 1.7.1 version you can use 'delegate' instead of "on" with slightly different syntax.
EDIT2: Discussion on the difference between .delegate, .live, and .bind here: http://brandonaaron.net/blog/2010/03/4/event-delegation-with-jquery
but with version 1.7 forwards you can use .on() instead.
$(( '.' + selectorString) ).bind( 'click' , function(){});
Is the proper way !
What you have there is correct for the selector assuming the html element is in place. You can use bind, but I prefer click.
$('.' + selectorString).click(function() {
alert('Handler for .click() called.');
});
More info on the jQuery site about click: http://api.jquery.com/click/