jQuery Mobile elements not displaying properly - javascript

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.

Related

How to check whether the input name contains specific value using if loop in jquery

i have a table with values. some of values ends with specific string so i want to check whether input name attribute contains specific string using if loop.
i have tried using below code but it is not working:
$("#tabTax tbody tr").each(function () {
if (this.name.endswith('taxtype')) {
$(this).replaceWith('<tr id="rowTax' + $(this).find("input[name$='taxtype']").val() + '><td hidden="hidden"></td><td> ' + $(this).find("input[name$='taxtype']").val() + '(' + parseFloat($(this).find("input[name$='Taxperce']").val()) + '%)</td><td><input type="text" name= Bookingtax[' + rowcount + '].TaxAmount disabled="disabled" class="form-control chargesinputfield" value=' + ($(this).find("input[name$='Taxperce']").val() * sum / 100).toFixed(2) + '></input></td><td hidden="hidden"><input name=Bookingtax[' + rowcount + '].TaxID id=' + $(this).find("input[name$='TaxID']").val() + ' type="text" class="form-control" value=' + $(this).find("input[name$='TaxID']").val() + ' ></input></td><td hidden="hidden"><input name=Bookingtax[' + rowcount + '].taxtype id=' + $(this).find("input[name$='taxtype']").val() + ' type="text" class="form-control" value=' + $(this).find("input[name$='taxtype']").val() + ' ></input></td><td hidden="hidden"><input name=Bookingtax[' + rowcount + '].Taxperce id=' + $(this).find("input[name$='Taxperce']").val() + ' type="text" class="form-control" value=' + $(this).find("input[name$='Taxperce']").val() + ' ></input></td><td hidden="hidden"><input name=Bookingtax[' + rowcount + '].TaxAmount id=' + $(this).find("input[name$='TaxAmount']").val() + ' type="text" class="form-control" value=' + ($(this).find("input[name$='Taxperce']").val() * sum / 100).toFixed(2) + ' ></input></td></tr>')
rowcount++;
} else {
$("#discountrate").replaceWith('<tr id="discountrate"><td> Discount</td><td hidden="hidden"></td><td><input type="text" name="Discountrate" id="txtDiscountrate" class="form-control chargesinputfield" value="' + $("#txtDiscountrate").val() + '"></input></td><td hidden="hidden"><input name=Bookingtax[' + rowcount + '].Taxperce id=' + $(this).find("input[name$='Taxperce']").val() + ' type="text" class="form-control" value=' + $(this).find("input[name$='Taxperce']").val() + ' ></input></td><td hidden="hidden"><input name=Bookingtax[' + rowcount + '].TaxAmount id=' + $(this).find("input[name$='TaxAmount']").val() + ' type="text" class="form-control" value=' + ($(this).find("input[name$='Taxperce']").val() * sum / 100).toFixed(2) + ' ></input></td></tr>')
}
})
I tried with this if (this.name.endswith('taxtype')), but it is not working.
Please help. Thanks in advance...
Try use $(this).is("[name$=taxtype]")
This will check if the name ends with the string taxtype ( $= means ends with)
Demo
$("#tabTax tr").each(function() {
if ($(this).is("[name$=taxtype]")) {
console.log("name ends with taxtype")
if ($(this).is("[name=taxtype]")) {
console.log("this only match taxtype")
}
} else {
console.log("name does not ends with taxtype")
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="tabTax">
<tr></tr>
<tr name="taxtype"></tr>
<tr></tr>
<tr name="somethingtaxtype"></tr>
</table>

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";
}

Issue with rendering javascript with javascript

Basically I've had a headache trying to solve this, I want to create a few controls with JS (using jquery) but I also want to add a remove button for them, my attempt is below:
html:
<div class=col-lg-6>
<h1>Pieces</h1>
<form method=post>
<div id=pieces></div>
<button class='btn btn-success' id=addpiece>Add Piece</button>
<button class='btn btn-primary'>Submit</button>
</form>
</div>
And the JS:
$(document).ready(function(){
var counter = 1;
$("#addpiece").click(function (e) {
$("#pieces").append('<label>Piece ' + counter + ': </label><br>' +
'<p id=added'+counter+'><div class=row><div class=col-lg-2><label>Dimensions:</label></div>' +
'<div class=col-lg-10><input min=0 step=0.1 style=width:70px; type="number" name="width' +
counter + '" required>cm x ' +
'<input min=0 step=0.1 style=width:70px; type="number" name="height' +
counter + '" required>cm x ' +
'<input min=0 step=0.1 style=width:70px; type="number" name="length' +
counter + '" required>cm</div></div>' +
'<div class=row><div class=col-lg-2><label>Weight:</label></div>' +
'<div class=col-lg-10><input min=0.001 step=0.001 style=width:70px; type="number" name="weight' +
counter + '" required>KG<br>' +
'<input type=hidden name=counter value=' +
counter + '><button class="btn btn-danger" id="remove' + counter + '">X</button>\<script type="text\/javascript"\>' +
'$("#remove' + counter + '").click(function (e) { $( "#added'+counter+'" ).remove(); return false; } \<\/script\>' +
'</div></div></p><br>');
counter++;
return false;
});
});
Check out my fiddle for clearer view:
http://jsfiddle.net/c1Lv7ska/
Since you are dynamically creating the remove button, use event delegation to register the remove handler.
Also it is better if you have a container element which will contain all the elements for a piece, like the one I added(<div class="piece">) to wrap all the elements.
$(document).ready(function () {
var counter = 1;
$("#addpiece").click(function (e) {
$("#pieces").append('<div class="piece"><label>Piece ' + counter + ': </label><br>' + '<p id=added' + counter + '><div class=row><div class=col-lg-2><label>Dimensions:</label></div>' + '<div class=col-lg-10><input min=0 step=0.1 style=width:70px; type="number" name="width' + counter + '" required>cm x ' + '<input min=0 step=0.1 style=width:70px; type="number" name="height' + counter + '" required>cm x ' + '<input min=0 step=0.1 style=width:70px; type="number" name="length' + counter + '" required>cm</div></div>' + '<div class=row><div class=col-lg-2><label>Weight:</label></div>' + '<div class=col-lg-10><input min=0.001 step=0.001 style=width:70px; type="number" name="weight' + counter + '" required>KG<br>' + '<input type=hidden name=counter value=' + counter + '><button type="button" class="btn btn-danger remove" id="remove' + counter + '">X</button>' + '</div></div></p><br></div>');
counter++;
return false;
});
$("#pieces").on('click', '.remove', function(){
$(this).closest('.piece').remove()
})
});
Also read
Event binding on dynamically created elements?
Demo: Fiddle

JavaScript .replace doesn't work [duplicate]

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.

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