JavaScript .replace doesn't work [duplicate] - javascript

This question already has answers here:
Replace method doesn't work
(4 answers)
Closed 7 years ago.
I have the following JavaScript code, and I like to replace some strings, but I can't
$new_slide = '<div class="slide">' +
'<table>' +
'<tr>' +
'<td class="pictureContainer">' +
'<img src="/img/admin/slide-placeholder.svg" />' +
'<input type="hidden" name="slides[0][picture][id]" data-value="picture_id" />' +
'<input type="hidden" name="slides[0][picture][thumbnail]" data-value="picture_thumbnail" />' +
'<input type="hidden" name="slides[0][picture][original]" data-value="picture_original" />' +
'</td>' +
'<td class="fieldsContainer">' +
'<p>' +
'<label for="masthead_0">Masthead</label>' +
'<input type="text" data-value="masthead" name="slides[0][masthead]" id="masthead_0" />' +
'</p>' +
'<p>' +
'<label for="first_heading_0">Heading #1</label>' +
'<input type="text" data-value="first_heading" name="slides[0][first_heading]" id="first_heading_0" />' +
'</p>' +
'<p>' +
'<label for="second_heading_0">Heading #2</label>' +
'<input type="text" data-value="second_heading" name="slides[0][second_heading]" id="second_heading_0" />' +
'</p>' +
'<p>' +
'<label for="link_title_0">Link title</label>' +
'<input type="text" data-value="link_title" name="slides[0][link][title]" id="link_title_0" />' +
'</p>' +
'<p>' +
'<label for="link_url_0">Link URL</label>' +
'<input type="text" data-value="link_url" name="slides[0][link][url]" id="link_url_0" />' +
'</p>' +
'</p>' +
'<label for="target_0">Link Target</label>' +
'<select id="target_0" data-value="link_target" name="slides[0][link][target]">' +
'<option value="_self">' + z.self + '</option>' +
'<option value="_blank">' + z.blank + '</option>' +
'</select>' +
'</p>' +
'</td>' +
'</tr>' +
'</table>' +
'</div>';
var slide = {
"picture_id" : "45",
"picture_thumbnail" : "/thumbnail.jpg",
"picture_original" : "/original.jpg",
"masthead" : "Mast Head #1",
"first_heading" : "First Heading",
"second_heading" : "",
"link_title" : "Link Title #1",
"link_url" : "Link URL #1",
"link_target" : "Link target #1"
}
for(field in slide)
{
$new_slide.replace('data-value="' + field + '"', 'value="' + slide[field] + '"');
}
More spesific,
I like by iterating the slide variable to replace the "key" values in the $new_slide variable with the value in slide variables.
In turn, the sting
<input type="hidden" name="slides[0][picture][id]" data-value="picture_id" />
I like to be converted in
<input type="hidden" name="slides[0][picture][id]" data-value="45" />
as well the field
<input type="text" data-value="second_heading" name="slides[0][second_heading]" id="second_heading_0" />
I like to be converted in
<input type="text" data-value="" name="slides[0][second_heading]" id="second_heading_0" />
But my code seems that not working. Can somebody to help me ?

You have to change it like:
$new_slide = $new_slide.replace('data-value="' + field + '"', 'value="' + slide[field] + '"');
because replace function doesn't change the $new_slide value, it just returns the new modified string.

Related

Replace characters with javascript at onkeyup [duplicate]

This question already has answers here:
How to convert a number with comma as string into float number in Javascript
(2 answers)
Closed 2 years ago.
When i type in the price to the input, i want to change "," to ".", because i enter decimal numbers.
What am i doing wrong? Whit this function, i always get NaN.
If i try alert or something for test, that works fine.
function change_characters(where)
{
return where.replace(",", ".");
//return min_.replace(/,/g, ".");
}
function szorzas( sor_id )
{
termek_netto_egyseg_ar = $('#termek_netto_egyseg_ar-'+sor_id).val();
ajanlat_termek_mennyiseg = $('#ajanlat_termek_mennyiseg-'+sor_id).val();
rosszeg = ajanlat_termek_mennyiseg * termek_netto_egyseg_ar;
$("#termek_netto_reszosszeg-"+sor_id).val(rosszeg);
termek_netto_egyseg_ar = change_characters(termek_netto_egyseg_ar);
count_ossz_netto();
}
I add the html with javascript, and on the inputs, i call the szorzas() function.
function addsav_melleklet()
{
html = '<tr id="sav_row_melleklet' + sav_row_melleklet + '">';
html += '<td class="left"><div class="bc-wrapper"><input type="hidden" id="termek_id-'+sav_row_melleklet+'" name="ajanlat_termek_id[' + sav_row_melleklet + ']" value="" /> <input required type="text" autocomplete="off" class="form-control" name="ajanlat_termek_nev[' + sav_row_melleklet + ']" id="ajanlat_termek_nev-' + sav_row_melleklet + '" onKeyUp="autocomplet_search(' + sav_row_melleklet + ');" /><div class="bc-menu list-group country_list_id" id="country_list_id' + sav_row_melleklet + '"></div></div></td>';
html += '<td class="left"><input required type="text" class="form-control csere" id="ajanlat_termek_mennyiseg-'+sav_row_melleklet+'" onKeyUp="szorzas(' + sav_row_melleklet + ')" onchange="szorzas(' + sav_row_melleklet + ')" name="ajanlat_termek_mennyiseg[' + sav_row_melleklet + ']" /></td>';
html += '<td class="left"><input required type="text" class="form-control csere termek_netto_egyseg_ar" id="termek_netto_egyseg_ar-'+sav_row_melleklet+'" onKeyUp="szorzas(' + sav_row_melleklet + ')" onchange="szorzas(' + sav_row_melleklet + ')" name="ajanlat_termek_netto_egyseg_ar[' + sav_row_melleklet + ']" /></td>';
html += '<td class="left"><input required type="text" class="form-control termek_netto_reszosszeg" id="termek_netto_reszosszeg-'+sav_row_melleklet+'" name="ajanlat_termek_netto_ertek[' + sav_row_melleklet + ']" /></td>';
html += '<td class="right"><a class="btn btn-sm btn-danger" onclick="remove_sor('+sav_row_melleklet+');"><span class="glyphicon glyphicon-trash"></span></a></td>';
html += '</tr>';
$('#sav_melleklet_tbody').append(html);
sav_row_melleklet++;
}
your replace function, replaces only the first occurences, if you want to replace all occurence you have to use regexp:
function change_characters(where)
{
return where.replace(/,/g, ".");
//return where.replace(",", "."); <-- replace only first occurence
}

Can't get value from table td with quotes

Here I am creating dynamic table
function addToMLContainer(id, mlName, mlAddress) {
return '<td><s:text>' + mlName + ' ' + mlAddress + '</s:text></td>' +
'<td hidden="hidden">' + id + '<input name="mlId" type="hidden" value = "' + id + '" /></td>' +
'<td hidden="hidden"><input name="mlFullName" type="hidden" value = "' + mlName + ' ' + mlAddress + '" /></td>' +
'<td align="center"><img src="/delete.png" class="remove" onclick="this.closest(\'tr\').remove()"/></td>'
}
And here I am getting value of tr:
var t = document.getElementById("AddedMlsContainer");
for (var i = 1, row; row = t.rows[i]; i++) {
selectedMerchants = selectedMerchants + " " + row.cells[2].children[0].value + "\n";
}
The problem is I can't get value with double or single quotes like <I'm "blabla">
Finally I did it by removing input field and unnesessary td:
'<td>' + mlName + ' ' + mlAddress + '</td>' +
'<td hidden="hidden">' + id + '<input name="mlId" type="hidden" value = "' + id + '" /></td>' +
'<td align="center"><img src="/delete.png" class="remove" onclick="this.closest(\'tr\').remove()"/></td>'
Then I used innerHtml
var t = document.getElementById("AddedMlsContainer");
for (var i = 1, row; row = t.rows[i]; i++) {
selectedMerchants = selectedMerchants + " " + row.cells[0].innerHTML.replace(/ /g,'') + "\n";
}

getElementById not returning proper value (maybe syntax issue?)

I am using XSL to write this page, and when I hit a checkbox it sends the information to my javascript function. This all works in IE, but Chrome it does not. The problem is, after I hit the checkbox, the field comes back as "undefined" like so
<div id="Part1" value="0-SER-MN">undefined</div>
Where it is initially like
<div id="Part1" value="0-SER-MN">0-SER-MN</div>
My guess would be that the value being returned is "null" but I don't know why? Can anyone help? Thanks.
<td colspan="2">
<div>
<xsl:attribute name="id">Part<xsl:value-of select="position()"/></xsl:attribute>
<xsl:attribute name="value"><xsl:value-of select="Part"/></xsl:attribute>
<xsl:if test="ErrorMessage">
<input type="hidden" name="partNumber">
<xsl:attribute name="value"><xsl:value-of select="Part"/></xsl:attribute>
</input>
<input type="hidden" name="TempKey">
<xsl:attribute name="value"><xsl:value-of select="TempKey"/></xsl:attribute>
</input>
</xsl:if>
<xsl:value-of select="./Part"></xsl:value-of>
</div>
</td>
SO here is the javascript that is selected with the checkbox
function turnOnOrder(index, tempKey)
{
document.getElementById('Part' + index).innerHTML = '<input type="hidden" name="partNumber" value="' + document.getElementById('Part' + index).value + '"></input> <input type="hidden" name="TempKey" value="' + tempKey + '"/>' + document.getElementById('Part' + index).value;
document.getElementById('Location' + index).innerHTML = '<input type="hidden" name="location" value="' + document.getElementById('Location' + index).value + '"></input> ' + document.getElementById('Location' + index).value;
document.getElementById('Site' + index).innerHTML = '<input type="hidden" name="siteCode" value="' + document.getElementById('Site' + index).value + '"></input> ' + document.getElementById('Site' + index).value;
document.getElementById('PONumber' + index).innerHTML = '<input type="hidden" name="origPO" value="' + document.getElementById('PONumber' + index).value + '"></input><input size="20" maxlength="20" type="text" name="PONumber" value="' + document.getElementById('PONumber' + index).value + '"></input>';
document.getElementById('Quantity' + index).innerHTML = '<input type="hidden" name="OrderQty" value="' + document.getElementById('Quantity' + index).value + '"></input> ' + document.getElementById('Quantity' + index).value;
if(document.getElementById('viewPrice') == null)
document.getElementById('Price' + index).innerHTML = '<input type="hidden" name="Price" value="' + document.getElementById('Price' + index).value + '"></input> ';
else
document.getElementById('Price' + index).innerHTML = '<input type="hidden" name="Price" value="' + document.getElementById('Price' + index).value + '"></input> ' + document.getElementById('Price' + index).value;
document.getElementById('UserId' + index).innerHTML = '<input type="hidden" name="UserId" value="' + document.getElementById('UserId' + index).value + '"></input> ';
//document.getElementById('InactiveOverride' + index).innerHTML = '<input type="hidden" name="InactiveOverride" value="' + document.getElementById('InactiveOverride' + index).value + '"/>';
//document.getElementById('MpqMoqOverride' + index).innerHTML = '<input type="hidden" name="MpqMoqOverride" value="' + document.getElementById('MpqMoqOverride' + index).value + '"/>';
document.getElementById('Other' + index).innerHTML = '<input type="hidden" name="Supplier" value="' + document.getElementById('Supplier' + index).value + '"></input><input type="hidden" name="ICST" value="' + document.getElementById('ICST' + index).value + '"></input><input type="hidden" name="backflush" value="' + document.getElementById('backflush' + index).value + '"></input><input type="hidden" name="Billing" value="' + document.getElementById('Billing' + index).value + '"></input><input type="hidden" name="InactiveOverride" value="' + document.getElementById('InactiveOverride' + index).value + '"/><input type="hidden" name="MpqMoqOverride" value="' + document.getElementById('MpqMoqOverride' + index).value + '"/>';
}
This seems to be an javascript DOM access issue. And has nothing to do with xslt.
The problem is based on the difference between DOM property and html attributes and the different handling in browsers.
In most cases using the DOM property (dom-elment.attribute-name) should work. Because the browser synchronize html attribute to DOM property. But this does not happen (in Chrome etc.) for customer attribute (e.g your value attribute at div).
Therefore you should use
document.getElementById('Part' + index).getAttribute('value')
in replacement for document.getElementById('Part' + index).value
This should work in all reasonable modern browsers (e.g IE > 6)

jQuery Mobile elements not displaying properly

I am using jQuery Mobile to display a table.
However when i append a new row using addMore button, the display is off! Why is it so? it is suppose to follow the first row. Ans also, it is displayed in black theme on my browser... but it is suppose to be white as in the fiddle. why?
Here is my fiddle: http://jsfiddle.net/BgxKW/1/
this is the code to add new row
var addmore = '<tr><td style="text-align: center">' + currentIndex + '</td>' +
'<td class="small">' +
'<div data-role="fieldcontain" class="ui-hide-label">' +
'<label for="number_' + currentIndex + '">Response Number</label>' +
'<input type="text" name="number_' + currentIndex + '" id="number_' + currentIndex + '" value="" placeholder="Response Number"/>' +
'</div></td><td>' +
'<div data-role="fieldcontain" class="ui-hide-label">' +
'<label for="label_' + currentIndex + '">Description</label>' +
'<input type="text" name="label_' + currentIndex + '" id="label_' + currentIndex + '" value="" placeholder="Description "/>' +
'</div></td></tr>';
Also, how can i remove the row?
You want to do $(".config").trigger("create"); at the final to resolve style problem.
Updated fiddle link is
http://jsfiddle.net/BgxKW/7/
$("#addMore").click(function () {
currentIndex = $(".config tr:last td:first").text()
if(currentIndex == ""){currentIndex = 0}
currentIndex = parseInt(currentIndex) + 1
var addmore = '<tr><td style="text-align: center">' + currentIndex + '</td>' +
'<td class="small">' +
'<div data-role="fieldcontain" class="ui-hide-label">' +
'<label for="number_' + currentIndex + '">Response Number</label>' +
'<input type="text" name="number_' + currentIndex + '" id="number_' + currentIndex + '" value="" placeholder="Response Number"/>' +
'</div></td><td>' +
'<div data-role="fieldcontain" class="ui-hide-label">' +
'<label for="label_' + currentIndex + '">Description</label>' +
'<input type="text" name="label_' + currentIndex + '" id="label_' + currentIndex + '" value="" placeholder="Description "/>' +
'</div></td></tr>';
++currentIndex;
$('#labels .config tr:last').after(addmore);
$(".config").trigger("create");
});
$("#remove").click(function(){
$(".config tr:last").remove();
});
Note: I fixed the style problem and remove function.

Avoid breaking string when creating new element due to text value

In my web application I have created a form that will allow users to insert stories to an online newspaper.
In order to do this I have created a hidden table which I clone to allow users to create new stories which I later catch on the submit event of my form.
Here I am facing a problem regarding the contents of the story's text.
For example, if the story contains double quotes on it, it will break my string when creating a new element on the submit event, like so;
$("form").submit(function () {
var myForm = $(this);
// begin cover stories process
var stories = $("#newsBlock").find("table");
if (stories != undefined) {
stories.each(function (index) {
var cNew = new CoverNew($(this).find('[name="news_id"]').attr("value"), $(this).find('[name="editionDate"]').attr("value"), $(this).find('[name="newsTitle"]').attr("value"), $(this).find('[name="newsLink"]').attr("value"), $(this).find('[name="newsAuthor"]').attr("value"), $(this).find('[name="newsSource"]').attr("value"), $(this).find('[name="newsDescription"]').attr("value"), $(this).find('[name="newsImageListing"]').attr("value"), $(this).find('[name="newsImageStory"]').attr("value"), $(this).find('[name="newsImageStory_Author"]').attr("value"), $(this).find('[name="newsImageStory_Description"]').attr("value"), $(this).find('[name="newsVideo"]').attr("value"), $(this).find('[name="newsText"]').val(), $(this).find('[name="newsOrder"]').attr("value"));
var ids = '<input name="Cover[' + index + '].id" id="Cover[' + index + '].id" type="text" value ="' + cNew.id + '" style="display:none;" />';
var title = '<input name="Cover[' + index + '].title" id="Cover[' + index + '].title" type="text" value="' + cNew.title + '" style="display:none;" />';
var editionDate = '<input name="Cover[' + index + '].edition_date" id="Cover[' + index + '].edition_date" type="text" value="' + cNew.editionDate + '" style="display:none;" />';
var link = '<input name="Cover[' + index + '].link" id="Cover[' + index + '].link" type="text" value="' + cNew.link + '" style="display:none;" />';
var author = '<input name="Cover[' + index + '].author" id="Cover[' + index + '].author" type="text" value="' + cNew.author + '" style="display:none;" />';
var source = '<input name="Cover[' + index + '].source" id="Cover[' + index + '].source" type="text" value="' + cNew.source + '" style="display:none;" />';
var description = '<input name="Cover[' + index + '].description" id="Cover[' + index + '].description" type="text" value="' + cNew.description + '" style="display:none;" />';
var menuPicture = '<input name="Cover[' + index + '].photo_in_list" id="Cover[' + index + '].photo_in_list" type="text" value="' + cNew.menu_picture + '" style="display:none;" />';
var story_picture = '<input name="Cover[' + index + '].photo_in_news" id="Cover[' + index + '].photo_in_news" type="text" value="' + cNew.story_picture + '" style="display:none;" />';
var story_picture_description = '<input name="Cover[' + index + '].photo_in_news_desc" id="Cover[' + index + '].photo_in_news_desc" type="text" value="' + cNew.story_picture_description + '" style="display:none;" />';
var story_picture_author = '<input name="Cover[' + index + '].photo_in_news_author" id="Cover[' + index + '].photo_in_news_author" type="text" value="' + cNew.story_picture_author + '" style="display:none;" />';
var video = '<input name="Cover[' + index + '].video" id="Cover[' + index + '].video" type="text" value="' + cNew.video + '" style="display:none;" />';
var content = '<input name="Cover[' + index + '].content" id="Cover[' + index + '].content" type="text" value="' + cNew.content + '" style="display:none;" />';
var order = '<input name="Cover[' + index + '].order" id="Cover[' + index + '].order" type="text" value="' + cNew.order + '" style="display:none;" />';
myForm.append(ids);
myForm.append(title);
myForm.append(editionDate);
myForm.append(link);
myForm.append(author);
myForm.append(source);
myForm.append(description);
myForm.append(menuPicture);
myForm.append(story_picture);
myForm.append(story_picture_description);
myForm.append(story_picture_author);
myForm.append(video);
myForm.append(content);
myForm.append(order);
index++;
});
}
});
In the above process, I collect the tables cloned by the user which contain stories.
Inside the variable content I place the text of the story.
But by the way I am concatenating it, if the text contains a double quote, the string will be broken at that point.
Is there anything I could do with javascript (even pure javascript) to fix this problem?
Yes - do var content = '<input name="Cover[' + index + '].content" id="Cover[' + index + '].content" type="text" value="' + cNew.content.replace(/"/g, """) + '" style="display:none;" />';
Use string Replace, for example:
cNew.story_picture_description.replace(/"/g, """);
Another and cleaner way would be to copy the whole table with cloneNode und delete the values in the new table.
use the javascript function to replace the " with "
var content = content.replace(/"/g, "&quot");
You should definetely make use of some template engine. Even simple jquery template or micro-template will work fine.
// Template engine, yea that easy
function templ(str, data) {
for (var p in data)
str = str.replace(new RegExp('{'+p+'}','g'), data[p]);
return str;
}
var cNew = new CoverNew(...);
cNew.index = index;
var story = templ($('#story-content').html(), cNew);
myForm.append(story);
And also place all your html into container:
<script type="text/template" id="story-content">
<input name="Cover[{index}].id" id="Cover[{index}].id" type="text" value ="{id}" style="display:none;" />
<input name="Cover[{index}].title" id="Cover[{index}].title" type="text" value="{title}" style="display:none;" />
...
</script>
Of course it's a little bit more complecated. But your code becomes more maintainable and clean.

Categories