Why jQuery append() removes words after first blank space in string - javascript

I'm trying to dynamically generate a form after an ajax request. Below is the relevant code sample :
for (var i in response.responseJSON[0].fields) {
var field = response.responseJSON[0].fields[i];
$('#properties_form').append('<label for=' + i + '>' + i + '</label>' +
'<input id=' + i + ' value=' + field + '>');
}
My problem is that, when var i and var field are strings with blank spaces like "Hello world", my label and inputs will be like <label id="Hello" world=""> and <input value="Hello" world="">. However, the label text will be displayed correctly i.e. <label>Hello world</label>.
I've no idea what kind of sorcery that is, but I'll be very grateful for any help. Thanks in advance.

There's a much more robust way of doing this.
for (var i in response.responseJSON[0].fields) {
var field = response.responseJSON[0].fields[i];
$('#properties_form')
.append($('<label>').attr('for', i).text(i))
.append($('<input>').attr('id', i).val(field));
}
You won't have to worry about the content of the strings as jQuery and the DOM will handle it for you. Not to mention this is much easier to read.

Use " to enclose the attributes.
$('#properties_form')
.append('<label for="' + i + '">' + i + '</label>' +
'<input id="' + i + '" value="' + field + '">');
EDIT
This will break for the cases where the value for i is something like This "works". Best solution is to append as jQuery or JS objects rather than using HTML string just like Daniel's answer.
Following snippet contains the correct fix for this. Updated based on the answer from Daniel.
i = 'Hello "World"';
field = 'Hello "World"s';
$('#properties_form')
.append($('<label>').attr('for', i).text(i))
.append($('<input>').attr('id', i).val(field));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="properties_form"></div>

Related

HTML Element not being inserted

I'm working on a .NET Core project for my company where work orders are loaded from our SQL database using Entity Framework, filtered and then displayed as markers on a map through Google Maps API for our installers.
We have two types of filters: one that gets included in an Ajax POST, and one that filters locally to decrease load times and performance issues. What I'm trying to do is load the local filter items (lists that are included in the response when calling the initial Ajax POST). If the list of filter items exceeds 5 items, I want them to collapse to only 5 items and insert an anchor which expands (utilizes jQuery's toggle()) showing the rest of the items in that list.
This is the excerpt from the JavaScript function which takes care of that:
filterItems
.forEach((filterItem, i) => {
var localItem = '<label class="' + selectorContainerClass
+ ' selectorContainer" id="' + selectorContainerIdPrefix + filterItem.key
+ '"><input id="' + convertValToEng(filterItem.value)
+ '" type = "checkbox" class="filled-in navy" name="' + inputName
+ '" value="' + filterItem.key
+ '" onchange="localFilter(this, this.value)" /><span class="selector-value">'
+ filterItem.value
+ '</span> <span id="' + paramName + 'Cnt__' + filterItem.key
+ '" class="selector-count"></span></label ><br />';
document.querySelector("#" + colId).insertAdjacentHTML('beforeend', localItem);
if (i >= 5) {
$("#" + colId + " #" + selectorContainerIdPrefix + filterItem.key).addClass("collapse");
$("#" + colId + " #" + selectorContainerIdPrefix + filterItem.key).toggle(100);
$("#" + colId + " #" + selectorContainerIdPrefix + filterItem.key + " + br").toggle(100);
}
});
if (filterItems.length > 5) {
//TODO: Fix the bug here; the .filter-collapse element is not being inserted under local installers.
var newEl = '<a class="filter-collapse" onclick="toggleFilterExpand(false, this)";><i class="material-icons">expand_more</i></a>';
document.getElementById(colId).insertAdjacentHTML('beforeend', newEl);
}
I should be getting a newEl inserted under the "Installer" column (8 installers, 3 of them not being displayed), but I'm not. I've tried jQuery's after() and insertAfter() methods, but neither of those worked. newEl is being generated for the "Area" column, as it should, but for the "Installer" column it's not.
I've also tried inserting the element manually through the console window with the exact same code and it works.
Would appreciate some help with this as I feel lost regarding this issue.
Thanks.
It turned out to be a stupid mistake on my end where I was removing the element newEl from the all the other filter lists before inserting a new one to the currently iterated one.

jquery each loop write data for each div

I hope this makes sense. I have an onclick and I am trying to write this data for each div with this.
jQuery('.circle_counter_div').each(function() {
var tagtext = '[circlecounter rel="' + jQuery('.circle_size').val() + '"][/circlecounter]';
})
I am cloning items but I can only write the data for one of them. How do I write data for each cloned item?
So with the above example I want tagtext to equal
[circlecounter rel="' + jQuery('.circle_size').val() + '"][/circlecounter]
[circlecounter rel="' + jQuery('.circle_size').val() + '"][/circlecounter]
[circlecounter rel="' + jQuery('.circle_size').val() + '"][/circlecounter]
Full Code
HTML
<div class="sc_options circle_counter_div" id="clone_this" style="display: block;">
<input type="text" class="circle_size"/>
</div>
<div class="sc_options circle_counter_div" id="clone_this" style="display: block;">
<input type="text" class="circle_size"/>
</div>
<div class="sc_options circle_counter_div" id="clone_this" style="display: block;">
<input type="text" class="circle_size"/>
</div>
<input type="submit" class="sc_options circle_counter_div" id="insert" name="insert" value="<?php _e("Insert", 'themedelta'); ?>" onClick="insertcirclecountershortcode();" style="display:none"/>
Script
// Insert the column shortcode
function insertcirclecountershortcode() {
var tagtext;
var start;
var last;
var start = '[circlecounters]';
var last = '[/circlecounters]';
jQuery('.circle_counter_div').each(function() {
var tagtext = '[circlecounter rel="' + jQuery('.circle_size').val() + '"][/circlecounter]';
})
var finish = start + tagtext + last;
if (window.tinyMCE) {
window.tinyMCE.execInstanceCommand(window.tinyMCE.activeEditor.id, 'mceInsertContent', false, finish);
//Peforms a clean up of the current editor HTML.t
//tinyMCEPopup.editor.execCommand('mceCleanup');
//Repaints the editor. Sometimes the browser has graphic glitches.
tinyMCEPopup.editor.execCommand('mceRepaint');
tinyMCEPopup.close();
}
return;
}
Extended Answer: After some more information was provided perhaps you're just missing the index and value properties on the loop. Its hard to tell, since little sample code is provided.
$('.test').each(function(i,v) {
var tagtext = $(v).html();
console.log(tagtext);
})
http://jsfiddle.net/4xKvh/
Original Answer:
Use use classes instead of an Id. Id's are only suposed to be used once on a page.
Since there should only be one occurance jQuery is filtering the result down to 1, even though the markup may have multiple elements with that Id on the page. This is to make use of the built-in browser function getElementById().
For proof checkout this jsFiddle
Using the class attribute is more appropriate for what you're trying to do.
jQuery('.clone_this').each(function() {
var tagtext = '[something][/something]';
})
And the markup:
<div class="clone_this"></div>
This will allow jQuery to return an array of elements like you're looking for
This is what I needed... Finally got it working.
tagtext = ' ';
jQuery('#circle_counter_div .circlecounter').each(function() {
tagtext += '[circlecounter rel="' + jQuery('.circle_size').val() + '" datathickness="' + jQuery('.circle_thickness').val() + '" datafgcolor="' + jQuery('.circle_color').val() + '" text="' + jQuery('.circle_text').val() + '" fontawesome="' + jQuery('.font_awesome_icon').val() + '" fontsize="' + jQuery('.circle_font_size').val() + '"][/circlecounter]';
});
var start = '[circlecounters]';
var last = '[/circlecounters]';
var finish = start + tagtext + last;

Browser window shows correct value in inspector but invalid in the document

I am dynamically generating the input box using jquery and then embedding it into the document. The problem I am having is, although the correct value is being shown in the inspector, the browser shows an invalid value.
To be further clear, here is the image:
You can see that, in the inspector
<input name="txtTblAmount" class="num" style="width:70px;" type="text" value="1000" tabindex="29">
the value is 1000 while that being shown in the browser window is 1500. Can anyone please have a look and tell me, what's the problem here?
P.S: Have tried it in firefox as well. But still the problem is same i.e. different value in the inspector.
Here is the JS code:
function addrow(itemName, itemid, godown, godownid, quantity, rate, amount, gstAmount) {
gstAmount = typeof gstAmount !== 'undefined' ? gstAmount : '0';
if (typeof dTable1 != 'undefined') {
// dTable1.fnClearTable();
//$('#ItemRows').find('a[name="btnDelItem"]').off();
dTable1.fnDestroy();
// $('#ItemRows').empty();
}
//alert($('#ItemRows tr').length);
var strRow = '<tr id="row' + ($('#ItemRows tr').length + 1) + '">' +
'<td class="">' +
(($('#ItemRows tr').length + 1)) +
'</td>' +
'<td class="tdItemName" style="widtd: 250px">' +
itemName +
'<input name="hfItemId" style="width:200px;" type="hidden" value="' + itemid + '"/>' +
'</td>' +
'<td class="" style="widtd: 200px">' +
godown +
'<input name="hfGodownid" style="width:200px;" type="hidden" value="' + godownid + '"/>' +
'</td>' +
'<td class="" style="widtd: 200px">' +
'<input name="txtTblQuantity" style="width:200px;" class="num" type="text" value="' + quantity + '"/>' +
'</td>' +
'<td class="" style="widtd: auto">' +
'<input name="txtTblRate" style="width:70px;" class="num" type="text" value="' + rate + '"/>' +
'</td>' +
'<td class="" style="widtd: auto">' +
'<input name="txtTblAmount" class="num" style="width:70px;" type="text" value="' + amount + '"/>' +
'</td>' +
'<td>' +
'<input name="txtTblGstAmount" class="num" style="width:70px;" type="text" value="' + gstAmount + '"/>' +
'</td>' +
'<td class="ms"><div class="btn-group1"> <a class="btn btn-small" rel="tooltip" data-placement="left" data-original-title=" edit " name="btnDelItem" data-id="' + ($('#ItemRows tr').length + 1) + '" ><i class="icon-remove"></i></a> </div></td>' +
'</tr>';
console.log(strRow);
console.log(amount);
$('#ItemRows').append(strRow);
//SaveNewParty($("#drpAccId option:selected").text());
bindGrid();
//dTable1.fnDraw();
PopulateTotal();
// $('#ItemRows').find('a[name="btnDelItem"]').off();
var insertedRow = $('#ItemRows tr')[$('#ItemRows tr').length - 1];
$(insertedRow).find('a[name="btnDelItem"]').on('click', function () {
var row = $(this).parents('tr');
dTable1.fnDeleteRow(dTable1.fnGetPosition(row[0]));
$('#ItemRows tr').each(function (index) {
$(this).find('td:nth(0)').text((index + 1));
});
PopulateTotal();
})
$('#datatable_Items').css('width', '100%');
Populate_Events();
}
I just had a look at your code and found that there was no problem in the code you have shown us here. I agree with Afzaal Ahmad Zeeshan but the way he has explained it, it's not always the case. I recently had the same issue and after hours of scratching my head I found out that the value was being changed by some other jquery code.
Also note that, it is not always the case that the value set by the jquery is shown in the inspector for example, if you try $("#inputel").val(4), you will note that the value will not be updated in the inspector but in the backend this value has been updated. Inspector only shows the value that was sent from the server, not the one you set by jquery or something else.
Hope you got my point!
Kamran, that's of no importance. You are setting this value NOT DYNAMICALLY. Yes, you can see here! You are either setting this value while loading the page, or you are using some other code, that you are not showing us! I am not sure of that. Ok here.
In my example you can see, I am writing a text in the input but there is no value update in the element's inspection.
Also, its maybe not the answer but you can see that you're using widtd which is not a correct CSS property. The correct one is width. You know that.
I am sure you won't get any problem while sending the form to the server, as the value will get updated by the value that you just wrote.
I have seen your code, you are writing the field as:
<input name="txtTblAmount" class="num"
style="width:70px;" type="text" value="' + amount + '"/>'
According to me, the issue is at amount. You are havin this field in the function too.
function addrow(itemName, itemid, godown,
godownid, quantity, rate, amount, gstAmount) {
Now what you can do to prevent that is to change the value of amount there. If you donot want to change it, then its OK. And also, once again you should not fear this value difference, as once you click submit the value that you have entered will be sent to the server instead of value of the field itself. The value is just because you have it written there. Nothing else, so don't worry! Its ok. You cannot change the value now, if you want to. Then here is the hell code, you will have to hard code it. Like this!
<div id="input">
<input type="text" id="text" value="" onkeyup="updateVal()" />
</div>
function updateVal() {
// start function..
var val = $('#text').val(); // the value of field..
// after getting the value, update the div..
$('#input').html("<input type='text' id='text' value='" +
val + "' onkeyup='updateVal()' />");
}
But note, after using this code, you will get the current value in the field! But you will loose the focus on the input field. As the div will get updated but the values will be the newest ones!
Now to keep in focus?
You can use this:
$('#text').focus();
But while using this, you will get only one ONLY ONE word in the field.
Why?
Because once if will focus on the field, it will (select all) select the words or value inside the field and when you press another word, it will replace the previous one with the latest one! This way you will not get any correct field I mean the field of your choice! But you issue will be fixed.
So kamran believe me, let it be the way it is! You donot want to hard-code it. If you still wanna give it a try, use the code I shared!
Example for the code I am sharing is as under:
Now when you right the value or some words, you will get the value auto updated when you see this Developer Tools. Like this:
That was all. I gave you two options for your work. And still I will love to go with the option of Not using a code, to just update the value on the field. Rest is upto you Kamran.
Edit:
You mentioed that you want to use the value 1000 not the value that the user would add to the input. Then use this:
$("name='txtTblAmount'").val() == "1000");
This will automatically override the value that user will add and replace it with the value that you want to get!

How to dynamically load telerik datepicker using javascript

how to load telerik datepicker dyanlically.
i am constructing a div tag with, html textbox and thought of appending telerik datepicker, can this be done, and can someone explain me the way to do it.
<div id="mainDiv">
str +='<div class="Subdiv" id=';
str += data.id + ' rel="' + relData + '"><br/>Date Question<br/><label>';
str += data.Question + "<br/><input type='textbox' id='Date'/></br></br>";
str += "<input type='button' value='Submit' onclick='Submitdate(\"" + data.previousdate+"\",\"" + data.id+ "\",\"" + data.changetype+ "\")'/>"; } $('#Date').appendTo(document.body).tDatePicker();
str += '</label></div>'; $('#mainDiv').append(str);
i am getting an error $('#Date').appendTo(document.body).tDatePicker(); is not a function.
Try this:
Register datepicker client side library:
$(Html.Telerik().ScriptRegistrar().DefaultGroup(group => group.Add("telerik.common.js").Add("telerik.datepicker.js")))
Create an input element on your form:
<input id="DatePickerInput" />
Then add the following javascript somewhere on the page:
$('#DatePickerInput').appendTo(document.body);
$('#DatePickerInput').tDatePicker();
or
$('#DatePickerInput').appendTo(document.body).tDatePicker();
To set a date value:
$('#DatePickerInput').val('5/29/2012'); //Date format may vary, you'll need to adjust it!
Good luck!
use:
var datePicker = $("<input>", { id: "Date", value: "1/1/2013"})
.appendTo(document.body);
datePicker.tDatePicker();
That should work!

Jquery append() isn't working

I have this <ul>
<ul id="select_opts" class="bullet-list" style="margin-left:15px;"></ul>
This javascript code which is meant to go throug a JSON object and add the options
to the UL:
$.each(q.opts, function(i,o)
{
var str='';
str+="<li id='li_" + i + "'><input type='text' id='opt_" + i + "' value='" + o.option + "'>";
str+=" (<a href='javascript:delOpt(" + i + ");'>Delete</a>) </li>";
$("#select_opts").append(str);
});
If I do console.log() I can see that the looping is working. If I do:
console.log($("#select_opts").html());
It shows the HTML being updated as expected. However in the browser window, it shows the
UL as empty!
What am I doing wrong?
$("select_opts").append(str);
should be
$("#select_opts").append(str);
you're referring to object by id so you missed #
$.each(q.opts, function(i,o)
{
var str='';
str+="<li id='li_" + i + "'><input type='text' id='opt_" + i + "' value='" + o.option + "'>";
str+=" (<a href='javascript:delOpt(" + i + ");'>Delete</a>) </li>";
$("#select_opts").append(str);
// ^
}
I can't really see what's wrong, but try this instead, just to see if it works...
$(str).appendTo("#select_opts");
Both should work.
Is this a typo?:
$("select_opts").append(str);
Did you mean?:
$("#select_opts").append(str);
UPDATED:
Try this:
$.each(q.opts, function(i, o) {
var li = $('<li>').attr('id', 'li_' + i);
var in = $('<input>').attr('type', 'text').attr('id', 'opt_' + i).val(o.option);
var aa = $('<a>').attr('href', 'javascript:delOpt(' + i + ');').text('Delete');
li.append(in).append(aa)
$("#select_opts").append(li);
});
The tag Input should be closed - if don't, when using not valid html in append() on Internet Explorer, the div is not put into DOM tree, so you cannot access it with jQuery later.
I'd imagine input needs to be properly self-closed.
I found the bug, another part of the code was emptying the <ul> when i clicked a certain button.

Categories

Resources