I've a Javascript with Jquery.
http://jsfiddle.net/P5gD7/3/
var libelle = 'tes\'te';
var id = 1;
var toAdd = "<input type='text' name='choix[" + id + "]' value='" + libelle + "' />";
$("#test").append(toAdd);
The problem is when I've a quote in "libelle" variable (i've escaped this quote), when I use append, Jquery put only tes in the "value" attribute.
I have to do with simple quote.
For info an alert(toAdd) return me the entire input with no errors.
Any ideas ?
Thanks
If you use jQuery to create the element for you through properties instead of string manipulation you can avoid these kind of problems:
var libelle = 'tes\'te';
var id = 1;
$('<input />', {
type: 'text',
name: 'choix[' + id + ']',
value: libelle
}).appendTo('#test');
Example fiddle
One approach here is to create the element, then set the value on that element. These can be chained together something like:
var libelle = "tes'te";
var id = 1;
var toAdd = "<input type='text' name='choix[" + id + "]' />";
// create the element, show and finally set the value (.val)
$(toAdd).appendTo("#test").val(libelle);
See The Fiddle Here
Related
I have a form I enter student info (name, email, address) and I was able to add a new row (made of three columns) using JS after I click a button. Every time a new row is created, three new columns are created with three input boxes each with its own element ID. So far so good. However, now I can't for the life of me figure out how to remove the last row that was added. Below is my code:
var student_ids = 0;
document.getElementById("studentCount").value = student_ids;
function anotherStudent(){
document.getElementById("student_info").innerHTML +=
"<div class='section colm colm4'>"+
"<input type='text' name='stud_name_" + student_ids + "'id='stud_name_" +student_ids+ "'class='gui-input' placeholder='Student name'>"+
"</div><!-- end section -->" +
"<div class='section colm colm4'>" +
"<input type='email' name='stud_email_" + student_ids + "'id='stud_email_" + student_ids + "'class='gui-input' placeholder='Email'>" +
"</div><!-- end section -->" +
"<div class='section colm colm4'>" +
"<input type='text' name='stud_address_" + student_ids + "'id='stud_address_" + student_ids + "'class='gui-input' placeholder='Address'>"+
"</div><!-- end section -->" ;
student_ids = ++student_ids;
document.getElementById("studentCount").value = student_ids ;
}
function removeStudent(){
var x = document.getElementById('stud_name_'+student_ids);
var y = document.getElementById('stud_email_'+student_ids);
var z = document.getElementById('stud_address_'+student_ids);
x.remove();
y.remove();
z.remove();
}
Edit:
You are not removing the divs, only the inputs themselves. You are also incrementing the student_ids global variable after you insert a row. This means that the removeStudent() function will always try to remove a non-existing row.
It would be better to pass the desired student_ids to removeStudent(), or manually de-increment the value.
In older environments (such as Explorer):
You cannot directly remove DOM elements from JavaScript. It's a bit unintuitive, but you have to go to the parent of that element and remove it from there:
var element = document.getElementById('stud_name_'+student_ids);
element.parentNode.removeChild(element);
This question already has answers here:
Pass a string parameter in an onclick function
(27 answers)
Closed 3 years ago.
I am building an HTML line in jQuery to append to a table in the HTML and want to capture when the input value changes. I am trying to pass a variable obj.attNewChum in the onchange attibute as follows:
contents = contents + "<input type='text' id='" + obj.cdId + "' name='" + obj.cdId + "' value='" + attMeeting + "' onchange='attendanceUpdateFunction(this.id, this.value, "+obj.attNewChum+")'>";
However, this gives the following error in the console:
Uncaught ReferenceError: N is not defined
at HTMLInputElement.onchange (Attendance.html:1)
attendanceUpdateFunction(this.id, this.value, N)
The variable obj.attNewChum does contain the value N.
I have tried putting the variable in quotes:
contents = contents + "<input type='text' id='" + obj.cdId + "' name='" + obj.cdId + "' value='" + attMeeting + "' onchange='attendanceUpdateFunction(this.id, this.value, "+"\"'obj.attNewChum'\""+")'>";
And that gives the following error in the console:
Uncaught SyntaxError: Invalid or unexpected token
The best alternative would be to attach the listener properly using Javascript instead, without using inline handlers, that way you don't have to deal with any escaping issues:
const input = $("<input>")
.prop({
id: obj.cdId,
name: obj.cdId,
value: attMeeting
});
input.on('change', function() {
attendanceUpdateFunction(this.id, this.value, obj.attNewChum);
});
Note that this results in the input being a jQuery object rather than a string, so rather than concatenating the new HTML, you would want to .append the new element.
If, by chance, you're just using the id to try to pass the obj.cdId to attendanceUpdateFunction, you might consider removing the id entirely and just use the plain reference to cdId:
const input = $("<input>")
.prop({
name: obj.cdId,
value: attMeeting
});
input.on('change', () => {
attendanceUpdateFunction(obj.cdId, input.val(), obj.attNewChum);
});
Use as follows
contents = contents +'<input type="text" id="'+obj.cdId+'" name="'+obj.cdId+'" value="'+attMeeting+'" onchange="attendanceUpdateFunction(this.id, this.value, \''+obj.attNewChum+'\'")">';
I am bringing a big html string inside an ajax call that I want to modify before I use it on the page. I am wondering if it is possible to edit the string if i store it in a variable then use the newly edited string. In the success of the ajax call this is what I do :
$.each(data.arrangement, function() {
var strHere = "";
strHere = this.htmlContent;
//add new content into strHere here
var content = "<li id=" + this.id + ">" + strHere + "</li>";
htmlContent is the key for the chunk of html code I am storing in the string. It has no problem storing the string (I checked with an alert), but the issue is I need to target a div within the stored string called .widgteFooter, and then add some extra html into that (2 small divs). Is this possible with jquery?
Thanks
Convert the string into DOM elements:
domHere = $("<div>" + strHere + "</div>");
Then you can update this DOM with:
$(".widgetFooter", domHere).append("<div>...</div><div>...</div>");
Then do:
var content = "<li id=" + this.id + ">" + domHere.html() + "</li>";
An alternative way to #Barmar's would be:
var domHere = $('<div/>').html( strHere ).find('.widgetFooter')
.append('<div>....</div>');
Then finish with:
var content = '<li id="' + this.id + '">' + domHere.html() + '</li>';
You can manipulate the string, but in this case it's easier to create elements from it and then manipulate the elements:
var elements = $(this.htmlContent);
elements.find('.widgteFooter').append('<div>small</div><div>divs</div>');
Then put the elements in a list element instead of concatenating strings:
var item = $('<li>').attr('id', this.id).append(elements);
Now you can append the list element wherever you did previously append the string. (There is no point in turning into a string only to turn it into elements again.) Example:
$('#MyList').append(item);
I'd like to build a string based on values defined in an html form only if they have been populated. I've successfully parsed the form fields and dropdown with a for loop ($.each()) but my ultimate goal is to dynamically build a string with the results. The string is being used to create a REST query, this is currently the only way to search based on our technologies. Does anyone have a recommended solution?
thx in advance
sample html element:
<input data-param=" prefix like '%" data-name="prefix" class="prefix uno" type="text" placeholder="pre">
working btn click event loop to capture filled in form fields:
var children = $(this).parent().children('.uno');
$.each(children, function(i, val){
if($(val).val() !== ''){
console.log($(val).data('name') + " "+ $(val).data('param') + " " + $(val).val());
}
});
goal:
var newString = field1.param + field1.val + '% ' + field2.param + field2.val + '% ';
translated:
var newString = prefix like '%01%' and name like '%tree%';
Thanks David Fregoli for the jquery serialize reference, that was close, but the solution ended up being to place the strings into a single array, change it toString(), and remove the ',' from the new string.
code:
var samp = [],
thisVal = $(this).parent().children('.uno');
$.each(thisVal, function(i, val){
if($(val).val() !== ''){
samp.push(
$(val).data('param'),
$(val).val(),
$(val).data('close')
);
}
});
itQuery.where = samp.toString().replace( /,/g , '');
result search string:
"number like '%08%' and field = 34"
I have a string with multiple elements with id's like below:
var data = "<div id='1'></div><input type='text' id='2'/>";
Now I'm using this regex to find all the id's in the string:
var reg = /id="([^"]+)"/g;
Afterwards I want to replace all those id's with a new id. Something like this:
data = data.replace(reg, + 'id="' + reg2 + '_' + numCompare + '"');
I want reg2, as seen above, to return the value of the id's.
I'm not too familiar with Regular Expressions, so how can I go about doing this?
Instead of using regex, parse it and loop through elements. Try:
var data = "<div id='1'></div><div id='asdf'><input type='text' id='2'/></div>",
numCompare = 23,
div = document.createElement("div"),
i, cur;
div.innerHTML = data;
function updateId(parent) {
var children = parent.children;
for (i = 0; i < children.length; i++) {
cur = children[i];
if (cur.nodeType === 1 && cur.id) {
cur.id = cur.id + "_" + numCompare;
}
updateId(cur);
}
}
updateId(div);
DEMO: http://jsfiddle.net/RbuaG/3/
This checks to see if the id is set in the first place, and only then will it modify it.
Also, it is safe in case the HTML contains a comment node (where IE 6-8 does include comment nodes in .children).
Also, it walks through all children of all elements. In your example, you only had one level of elements (no nested). But in my fiddle, I nest the <input /> and it is still modified.
To get the get the updated HTML, use div.innerHTML.
With jQuery, you can try:
var data = "<div id='1'></div><div id='asdf'><input type='text' id='2'/></div>",
numCompare = 23,
div = $("<div>"),
i, cur;
div.append(data);
div.find("[id]").each(function () {
$(this).attr("id", function (index, attr) {
return attr + "_" + numCompare;
});
});
DEMO: http://jsfiddle.net/tXFwh/5/
While it's valid to have the id start with and/or be a number, you should change the id of the elements to be a normal identifier.
References:
.children: https://developer.mozilla.org/en-US/docs/DOM/Element.children
.nodeType: https://developer.mozilla.org/en-US/docs/DOM/Node.nodeType
jQuery.find(): http://api.jquery.com/find/
jQuery.attr(): http://api.jquery.com/attr/
jQuery.each(): http://api.jquery.com/each/
Try using
.replace(/id='(.*?)'/g, 'id="$1_' + numCompare + '"');
Regex probably isn't the right way to do this, here is an example that uses jQuery:
var htmlstring = "<div id='1'></div><input type='text' id='2'/>";
var $dom = $('<div>').html(htmlstring);
$('[id]', $dom).each(function() {
$(this).attr('id', $(this).attr('id') + '_' + numCompare);
});
htmlstring = $dom.html();
Example: http://jsfiddle.net/fYb3U/
Using jQuery (further to your commments).
var data = "<div id='1'></div><input type='text' id='2'/>";
var output = $("<div></div>").html(data); // Convert string to jQuery object
output.find("[id]").each(function() { // Select all elements with an ID
var target = $(this);
var id = target.attr("id"); // Get the ID
target.attr("id", id + "_" + numCompare); // Set the id
});
console.log(output.html());
This is much better than using regex on HTML (Using regular expressions to parse HTML: why not?), is faster (although can be further improved by having a more direct selector than $("[id]") such as giving the elements a class).
Fiddle: http://jsfiddle.net/georeith/E6Hn7/10/