dynamically added element is not wired on jquery event - javascript

on dom ready I have wired event
$('.someClass').on('input', function (e) {
// do something
});
on same I'm injecting html elements with where I add .someClass to include that field for same event
var cssClass = "form-control";
if (myProperty == true) {
cssClass = "form-control someClass";
}
('#myTable tr:last').after(
'<tr>'+
'<td><input class=' + cssClass + ' type="text"'</td></tr>'+
'</tr>'
);
but I'm getting rendered inside firebug as
<input class="form-control someClass" type="text"</td someClass="">
and this field is not fetched on .someClass event

the solution is to write:
$('body').on('input','.someClass', function (e) {
// do something
});
and fix your code:
$('#myTable tr:last').after(
'<tr>'+
'<td><input class=' + cssClass + ' type="text"/></td></tr>'
);

Mmm... aren't you missing the quotation mark (") in the input's class?
Furthermore, you are not correctly appending the td and tr closing tags. Try something like this:
$('#myTable tr:last').after(
'<tr>' +
'<td><input class="' + cssClass + '" type="text" /></td>' +
'</tr>'
);

Related

How to set html id to a variable

$('#submit').click(
function (event) {
event.preventDefault();
let number = 0;
$("#tasklist").append("<li id='addedtask number'>" + $('#task_to_add').val() + "</li>" +
"<form action='index.html' method='get'> <input type='submit' id='remove index' value='remove'></input> </form>");
}
);//end of submit
I am adding this button dynamically with jquery and I would like to increment the id of this button, how would I do this?
I would like it to be equivalent of this after the first time it should be:
<input type='submit' id='remove index 1' value='remove>
and after second:
<input type='submit' id='remove index 2' value='remove>
If I try to put a variable int the id like 'remove index myvar' i think it will just treat myvar like a string. Is there a way to get to be treated like a variable?
Please advise and thanks.
var currentId = 1;
$("#submit").click(function(event) {
event.preventDefault();
$("#tasklist").append(
"<li id='addedtask'>" +
$('#task_to_add').val() +
"</li>" +
"<form action='index.html' method='get'>" +
"<input type='submit' id='remove-index-" + currentId++ + "' value='remove'></input>" +
"</form>"
);
});

How can I call a jquery function on selecting a dropdown option for dynamically created inputs?

So this is what the page looks like currently:
The first one is hardcoded in and then the rest are added/removed by the buttons. The first one can also be added and removed from the buttons. I want to call a jquery function when the dropdown is changed to change the type from textbox/radiobutton (and text)/checkbox (and text) etc.
Currently it only works on the first Question/Answer and only works if it is the original and not dynamically created. I'm not sure why that is.
Here is how the Q/A's are created and removed
$("#addButton").click(function () {
if (counter > max_fields) {
alert("Only " + max_fields + " Questions allowed");
return false;
}
var newTextBoxDiv = $(document.createElement('div'))
.attr("id", 'TextBoxDiv' + counter);
newTextBoxDiv.after().html('<label>Question #' + counter + ' : </label>' +
'<input type="text" name="textbox' + counter +
'" id="questionbox' + counter + '" value="" />' +
' <select id="choice'+ counter +'"><option>Type</option><option>Radio Button</option><option>Text Box</option><option>Check Box</option></select>' +
'<button id = "remove' + counter + '">Remove</button>' +
'<br/><label>Answer #' + counter + ' : </label>' +
'<div id="Answers' + counter + '">' +
'Option 1: <input type="text" id="answerbox' + counter +
'1" name="answerbox' + counter + '" value="" />' +
'<br/>Option 2: <input type="text" id="answerbox' + counter +
'2" name="answerbox' + counter + '" value="" />' +
'<br/>Option 3: <input type="text" id="answerbox' + counter +
'3" name="answerbox' + counter + '" value="" />' +
'<br/>Option 4: <input type="text" id="answerbox' + counter +
'4" name="answerbox' + counter + '" value="" /></div>');
newTextBoxDiv.appendTo("#TextBoxesGroup");
counter++;
});
$("#removeButton").click(function () {
if (counter == 1) {
alert("No more textbox to remove");
return false;
}
counter--;
$("#TextBoxDiv" + counter).remove();
});
This is how I tried to get it to change types
$('#choice1').change(function () {
var selected_item = $(this).val()
var searchEles = document.getElementById("Answers1").children;
alert(searchEles.length);
for(var i = 0; i < searchEles.length; i++) {
$('#answerbox1' + i).attr('type', selected_item);
//alert(searchEles.length);
}
});
The web page code is as follows
<input type='button' value='Add Question' id='addButton'/>
<input type='button' value='Remove Question' id='removeButton'/>
<div id='TextBoxesGroup'>
<div id="TextBoxDiv1">
<label>Question #1 : </label>
<input type='text' id='questionbox1'/>
<select id="choice1" onchange="$('#choice').val('id');"> //this on change was added and currently does nothing it seems.
<option value="">Type</option>
<option value="radio">Radio Button</option>
<option value="text">Text Box</option>
<option value="checkbox">Check Box</option>
</select>
<button id="remove1">Remove</button>
<br/><label>Answer #1 : </label>
<div id="Answers1">
Option 1: <input type="text" id='answerbox11' name='answerbox1' value="" />
<br/>Option 2: <input type="text" id='answerbox12' name='answerbox1' value="" />
<br/>Option 3: <input type="text" id='answerbox13' name='answerbox1' value="" />
<br/>Option 4: <input type="text" id='answerbox14' name='answerbox1' value="" />
</div>
</div>
</div>
I tried to do something like onchange and then get the ID and go from there but that didn't work. I know it doesn't match the back end jquery name.
TL;DR
I don't know how to dynamically write the jQuery function to work
for all of them.
I don't know why even if I hardcode it to #choice1 it will work
when its first created but not if i remove and add it even though it
has the same exact values. I think it might MAYBE have to do with
for loop, because the alert doesn't even trigger the second time
around.
You could try
$(document).on("change", ".selector", function(){
//do something
});
//Edit
Add to the select element class for example select-option and a tag that will hold the select's counter
//JS
...'<select id="choice'+counter+'" class="select-option" number="'+counter+'">'...
and then your on change function would look something like
$(document).on("change", ".select-option", function(){
//do something
var selected_type = $(this).attr('value');
var ans_number = $(this).attr('number');
$("#answerbox"+ans_number).children('input').attr('type', selected_type);
});
I hope this will help :)
For dynamically added elements use
$(selector).on("change", callback)
If element is dynamic then Jquery will not bind directly as
$('#choice1').change(function (){});
But for that you need to call same function with some static element.
For Ex:
$(".listingDiv").find('#choice1').change(function (){});
or
$(document).find('#choice1').change(function (){});
and it will work. try it.
When elements will be aded dynamically, best practice is to delegate the handler(s). Put your handler on the containing div or window/document
.
First
<select id="choice1" onchange="$('#choice').val('id');"> //this on change was added and currently does nothing it seems.
This is one reason your never be called. If you bind an event listener to an element, you should not write the actual JS code inside the element.
Second
Bind your listener like this:
$('#choice1').on("change", function () {
var selected_item = $(this).val()
var searchEles = document.getElementById("Answers1").children;
alert(searchEles.length);
for(var i = 0; i < searchEles.length; i++) {
$('#answerbox1' + i).attr('type', selected_item);
//alert(searchEles.length);
}
});

Accessing Textbox Value Using Inserted JavaScript

I'm Having a bit of an issue. I'm using JavaScript to inset HTML into a webpage along with an event handler for the onblur event. It looks like this:
return '<input id = "txtIn" type="text" value=" ' + dateTime + '" onblur= "submitManualDate(document.getElementById("txIn").value(), 2, 3);" />';
I'm getting a syntax error. However, the following works perfectly fine:
return '<input id = "txtIn" type="text" value=" ' + dateTime + '" onblur= "submitManualDate(1, 2, 3);" />';
Any idea what I'm missing?
Using " inside "(double quoted) expression will break the string.
It's better to pass this as an argument as you should not have multiple elements with same id attributes in a document.
Try this example:
(function() {
var input = '<input type="text" value="5" onblur= "submitManualDate(this, 2, 3);" />';
document.getElementById('parent').innerHTML = input;
})();
function submitManualDate(elem, j, k) {
alert(elem.value + ' ' + j + ' ' + k);
}
<div id='parent'></div>
Fiddle here

I have a styled td class that makes my comment button look like a submit

After text is entered in the textarea i would like to target this class to let the user submit by pressing enter.
cmnt += '<td class="cmnt_save" data-id="' + id + '">Save Comment</td>';
Everything I've tried has failed miserably.. i've tried using jquery, JS and some inline JS too.
Here's my function with my tables:
// This function retrieves comments
function get_comments(id ,afterCtl ,ctl) {
var cmnt = '';
show_loading('.loading_box');
// Create the new row in the database - ajax returns json version.
var add_url = '/ajax/project_comment_list.php?id=' + id;
var slot = $.getJSON(add_url)
.done(function(data) {
// Draw the entire comment-block then display it
cmnt = '<tr class="cmnts">';
cmnt += ' <td colspan="11">';
cmnt += ' <table>';
cmnt += ' <tr class="cmnt_add">';
cmnt += ' <td class="cmnt_text">'
cmnt += ' <input type="text" id="cmnt_new" name="cmnt_new" rows="1">';
//cmnt += ' <textarea id="cmnt_new" name="cmnt_new" rows="1"></textarea>';
cmnt += ' </td>';
cmnt += ' <td></td>';
cmnt += ' <td></td>';
cmnt += ' <td class="cmnt_save" data-id="' + id + '">Save Comment</td>';
cmnt += ' </tr>';
$.each(data.ProjectComments, function (index, value) {
cmnt += add_comment_row(value.TEXT ,blank_if_undefined(value.EMP_INIT) ,value.ENTER_DATE);
});
cmnt += ' </table>';
cmnt += ' </td>';
cmnt += '</tr>';
remove_comments(ctl);
$(afterCtl).after(cmnt);
$('#cmnt_new').focus();
$(ctl).addClass('cmnt_active');
$(ctl).html(' - ');
//register the event
$('td.cmnt_save').click(function(){
add_comment($(this));
});
comment_shown = id;
})
.fail(function(jqxhr, status, error) {
hide_loading('.loading_box');
show_error('There was an error pulling the comments.');
});
//wire up the event
$('textarea#cmnt_new').keydown(function(e) {
if(e.which == 13) {
e.preventDefault();
alert('Cripes! You pressed enter!');
}
})
}
If anyone could be of any help to get this task accomplished or just recommend other/better ways of making this function correctly. Thanks in advance for the help.
If I am understanding you correctly, you just want to save the comment the user added after the user hits the enter key in the relative text-area.
I think you want something like this: http://jsfiddle.net/5JKy8/2/
HTML
<table id="comments">
<tr>
<th>Name</th>
<th>Comment</th>
</tr>
<tr>
<td>Foo</td>
<td><textarea class="comment" rows="1" id="333"></textarea></td>
</tr>
<tr>
<td>Bar</td>
<td><textarea class="comment" rows="1" id="666"></textarea></td>
</tr>
</table>
Javascript
$(document).ready( function() {
$("body").on("keydown",".comment", function(e) {
if(e.which == 13) {
var comment = $(this).val(),
id = $(this).data("id");
saveComment(comment,id).done( function() {
$(this).parent("td").text(comment);
});
}
});
});
function saveComment(comment,id) {
return $.ajax({
url: 'yourScript.php',
data: {comment:comment,id:id}
});
}
Note: In the jsfiddle the saveComment() is returning a boolean for demo purposes, but just use the commented out code.
What's the ID of the text field..? #cmnt_new?
$('#static-parent').on('keyup', '#cmnt_new', function(ev){
if(e.keyCode == 13)
{
// do whatever here
}
});
Where #static-parent is something that is not dynamically loaded and #cmnt_new is inside of it (a parent). I believe you could even do $(document).on(... For scripts to work on dynamically loaded content, you have to use a delegate and go through something static on the page.
Use the Event Object's keyCode property onkeyup. event.keyCode === 13 for the enter button, like:
$('#cmnt_new').keyup(function(e){
if(e.keyCode === 13){
// do your thing here
}
});
Note, that you've combined <input type='text' /> closing it with </textarea>.

Script is working with jquery 1.3.2 but not with jquery 1.7.2

I am trying to add extra input fields but this code works with jquery 1.3 once i try with jquery 1.7. It doesn't work
var newTr = $(document.createElement('tr'))
.attr("id", 'line' + counter);
newTr.after().html('<td><input type="text" name="name' + counter +
'" id="name' + counter + '" value="" style="width:100px;"></td><td><input type="text" name="phone' + counter +
'" id="phone' + counter + '" value="" style="width:100px;"></td>');
newTr.appendTo("#dyTable");
I guess there is problem with newTr.after().html() and newTr.appendTo("#dyTable"); Please help me
document.createElement('tr') is not needed and you can simply use $('<tr></tr>') to create new element. This should work,
var newTr = $('<tr></tr>').attr("id", 'line' + counter);
For adding <td> content, change, newTr.after().html('...') to newTr.html('...'). I don't think after is required.

Categories