Sanitizing input to stick into a hidden input value with jQuery - javascript

Maybe I am confusing this a bit, but I have a piece of code that works like the following:
$("#myButton").on('click', function(){
var myValue = $('#myInput').val();
listSize++;
var listItem = "<li>" + myValue + "<input type='hidden' name='foo" +
listSize + "' value='" + myValue + "' /></li>";
$("ol.myList").append(listItem);
});
If the text input value contains for example, a ', then this code breaks in terms of correctly adding the hidden input value.
I was thinking that using encodeURIComponent would do the trick, but it does not.
What's the proper way to handle this?

Instead of doing this with html strings, create an actual element and set it's value property using val().
You can sanitize any possible html out of it by first inserting the string into a content element as text and retrieving it as text.
Note that the value property does not get rendered in the html the same as value attribute does so quotes are not an issue
$("#myButton").on('click', function(){
// sanitize any html in the existing input
var myValue = $('<div>', {text:$('#myInput').val())).text();
listSize++;
// create new elements
var $listItem = $("<li>",{text: myValue});
// set value of input after creating the element
var $input = $('<input>',{ type:'hidden', name:'foo'+listSize}).val(myValue);
//append input to list item
$listItem.append($input);
// append in dom
$("ol.myList").append($listItem);
});

I think this is what you are looking for:
$("#myButton").on('click', function(){
var myValue = $('#myInput').val();
listSize++;
var listItemHTML = "<li>" + myValue + "<input type='hidden' name='foo'></li>";
$(listItemHTML).appendTo('ol.myList').find('input[type=hidden]').val(myValue);
});
The appendTo function returns a reference to the just appended element.
Calling the val() function on the element will render the inserting of a quote useless since it will be interpreted as an actual value.

Safest way would be to write a wrapper
function addslashes (str) {
return (str + '')
.replace(/[\\"']/g, '\\$&')
.replace(/\u0000/g, '\\0')
}
var test= "Mr. Jone's car";
console.log(addslashes(test));
//"Mr. Jone\'s car"

Related

Loop around HTML variable and replace spans with content

I have a variable that contains HTML.
var html = '<p><span id="variable:7" class="variable-source" title="variable:TEXT_CONTAINER">DATA</span> This is a variable</p>'+
'<p><span id="input:10.New Input 2" class="input-source" title="New Screen; New Input 2">DATA</span> This is a input source</p>'+
'<p>Testing</p>';
I am trying to loop around all of the elements and replace with spans specific date. So any spans with a class of variable-source will need to be replaced with specific date, and the same for input-source.
I have tried to use the following:
$('span', html).replaceWith(function () {
var id = $(this).attr('id');
// this returns the correct id
//calculations go here
var value = 'testing';
return value
});
Which outputs the following:
testing This is a variable
All of the paragraph tags have been removed, and it seems to stop after the first paragraph. Is there something that I am missing here? I can post more code or explain more if needed.
Thanks in advance.
You need to create a html object reference, else you won't get a reference to the updated content. Then get the update content from the created jQuery object after doing the replace operations
var html = '<p><span id="variable:7" class="variable-source" title="variable:TEXT_CONTAINER">DATA</span> This is a variable</p>' +
'<p><span id="input:10.New Input 2" class="input-source" title="New Screen; New Input 2">DATA</span> This is a input source</p>' +
'<p>Testing</p>';
var $html = $('<div></div>', {
html: html
});
$html.find('span.variable-source').replaceWith(function() {
var id = this.id;
// this returns the correct id
//calculations go here
var value = 'replaced variable for: ' + id;
return value
});
$html.find('span.input-source').replaceWith(function() {
var id = this.id;
// this returns the correct id
//calculations go here
var value = 'replaced input for: ' + id;
return value
});
var result = $html.html();
$('#result').text(result);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="result"></div>

Replace selected text inside p tag

I am trying to replace the selected text in the p tag.I have handled the new line case but for some reason the selected text is still not replaced.This is the html code.
<p id="1-pagedata">
(d) 3 sdsdsd random: Subject to the classes of this random retxxt wee than dfdf month day hello the tyuo dsds in twenty, the itol ghot qwerty ttqqo
</p>
This is the javascript code.
function SelectText() {
var val = window.getSelection().toString();
alert(val);
$('#' + "1-pagedata").html($('#' + "1-pagedata").text().replace(/\r?\n|\r/g,""));
$('#' + "1-pagedata").html($('#' + "1-pagedata").text().replace(/[^\x20-\x7E]/gmi, ""));
$('#' + "1-pagedata").html($('#' + "1-pagedata").text().replace(val,"textbefore" + val + "textAfter"));
}
$(function() {
$('#hello').click(function() {
SelectText();
});
});
I have also created a jsfiddle of the code.
https://jsfiddle.net/zeeshidar/w50rwasm/
Any ideas?
You can simply do $("#1-pagedata").html('New text here');
Since your p doesn't content HTML but just plain text, your can use both html() or text() as getter and setter.
Also, thanks to jQuery Chaining you can do all your replacements in one statement. So, assuming your RegExp's and replacement values are correct, try:
var $p = $('#1-pagedata');
$p.text($p.text().replace(/\r?\n|\r/g,"").replace(/[^\x20-\x7E]/gmi, "").replace(val,"textbefore" + val + "textAfter"));

Dynamically added textbox with given value not added properly,jquery

I added textbox value as Baker's Basket, Pune, Maharashtra, Indiasd but on click event in textbox it only shows Baker's
I want to display whole text Baker's Basket, Pune, Maharashtra, Indiasd in the textbox.
JS FIDDLE EXAMPLE
// Try to Enter text given bellow
//Baker's Basket, Pune, Maharashtra, Indiasd
$("#clk").on('click', function () {
$("#cnt_div").empty();
var getTxt = $("#txt_n").val();
var addContent = "<input type='text' value=" + getTxt + " />";
$("#cnt_div").append(addContent);
});
without editng addContent variable
Edited:
JS FIDDLE SAMPLE TWO
$("#clk").on('click', function () {
var gData1 = $("#txt_1").val();
var gData2 = $("#txt_2").val();
var gData3 = $("#txt_3").val();
var cnt_1 = "<span class='lbl_normal_mode'>" + gData1 + "</span><input class='txt_edit_mode' value=" + gData1 + " type='text'/>";
var cnt_2 = "<span class='lbl_normal_mode'>" + gData2 + "</span><input class='txt_edit_mode' value=" + gData2 + " type='text'/>";
var cnt_3 = "<span class='lbl_normal_mode'>" + gData3 + "</span><input class='txt_edit_mode' value=" + gData3 + " type='text'/>";
var content_Data = "<div class='chunk_div_holder'><div style='float:left:width:100%'>" + cnt_1 + "</div><div style='float:left:width:100%'>" + cnt_2 + "</div><div style='float:left:width:100%'>" + cnt_3 + "</div></div>";
$(".dynmic_cntt").append(content_Data);
});
You should better append the element and its properties dynamically as an object:
$('<input>', {
type: 'text',
value: $("#txt_n").val()
}).appendTo($("#cnt_div").empty());
This will solve the problem of extra spaces (no quotes for value=Baker's Basket), wrong string escape (if the value will have quotes) for value attribute and other caveats.
N.B.: There is no textbox type for <input> element. It should be text instead.
DEMO: http://jsfiddle.net/ZyMCk/11/
Add the field in two stages:
add the field as you are already
set the value of the field using .val()
It is because you aren't escaping ' single quote.
Instead you can replace
this line
var addContent="<input type='textbox' value='"+getTxt+"' />";
with
var addContent=$("<input type='textbox' />").val(getTxt);
or
var addContent="<input type='textbox' value=\""+getTxt+"\" />";
Value attribute should enclose in quotes. In your case, its better to use double quotes, because Baker's Basket, Pune, Maharashtra, Indiasd already have a single quote in it.
$("#clk").on('click',function(){
$("#cnt_div").empty();
var getTxt=$("#txt_n").val();
var addContent="<input type='textbox' value=\""+getTxt+"\" />";
$("#cnt_div").append(addContent);
});
Fiddle
Edit
$("#clk").on('click',function(){
$("#cnt_div").empty();
var getTxt=$("#txt_n").val();
var addContent=$("<input/>",{type:"text",value:getTxt});
$("#cnt_div").append(addContent);
});
Updated fiddle
change "+getTxt+" to '"+getTxt+"'
fiddle
OR
change "+getTxt+" to \""+getTxt+"\"
Heres a better way of doing this...
var addContent=$("<input type='textbox' />").val(getTxt);
http://jsfiddle.net/ZyMCk/9/
Basically, if creating an element to append to the DOM your better off doing this as a jQuery object. This way we can take advantage of methods such as val() for adding the value.
UPDATE
Ive simplified things a bit for you...
JSFIDDLE: http://jsfiddle.net/ZyMCk/22/
$("#clk").on('click', function () {
$('.dynmic_cntt').empty();
$('.form-text').each(function(){
var $div = $('<div style="float:left:width:100%;"></div>');
var $span = $('<span class="lbl_normal_mode">'+ $(this).val() +'</span><input class="txt_edit_mode" value="'+$(this).val() +'" type="text"/>');
$('.dynmic_cntt').append( $div.append( $span ) );
});
});

How I find the checkbox by id and apply attribute on string using JQuery?

I have a following html string of contentString:
var content =
'<div id="content">' +
'<div>' +
'<input name="tBox" id="select" type="checkbox" value="" '+
'onclick="changeView()"> Select for operation' +
'<p style="text-align:right">View details</p>' +
'</div>' +
'</div>';
Here, How I find the checkbox select by id and add attribute checked on changeView() function?
function changeView(m) {
//find the select id from content string
var checkbox = content.find($('#select'+m));
// Apply the checked property on checkbox.
checkbox.attr("checked","checked");
}
Thanks in advance.
If you convert it to a JQuery object first then you can do it like this:
var contentObj = $(content);
var checkbox = contentObj.find("#select");
checkbox.attr("checked", true);
then if you need it back at html string:
content = contentObj[0].outerHTML;
Note: If outerHTML is not working as expected, the following JQuery can be used as an alternative:
content = contentObj.clone().wrap('<div>').parent().html();
If m is meant to be the id you want to find (e.g. "select"), then use this:
var checkbox = contentObj.find("#" + m);
Live Example: Here is a working example
Here is the complete function for easy reference:
function changeView(m) {
var contentObj = $(content);
var checkbox = contentObj.find("#" + m);
checkbox.attr("checked", true);
content = contentObj[0].outerHTML;
}
You need to compile the string into a DOM object first by wrapping it in a jQuery call first. Then you can use the find method.
So:
var dom = $(content),
select = dom.find('#select');
In any case, there is no need to add the 'checked' attribute, because when you click the checkbox, it will automatically become checked.
If however, you want to still programmatically check it:
select.on('click', function () {
this.attr('checked', 'checked');
});
Simply like this
function changeView(m) {
//find the select id from content string
var checkbox = content.find('#select');
// Apply the checked property on checkbox.
checkbox.attr("checked","checked");
}
if you want to pass id then
function changeView(m) {
//find the select id from content string
var checkbox = content.find("#" + m);
// Apply the checked property on checkbox.
checkbox.attr("checked","checked");
}
Since you're using the onclick handler, you don't really need to do any of that :
in html : onclick="changeView(this);"
function changeView(box) {
if(box.checked) { stuff; }
// or get jquery ref to that box :
$(box).prop("checked", true);
}

Different behavior with .val() and .attr("value") using ajax return data on a clone()'d but uninserted element

As the title says, I'm trying to set the value of a .clone()'d form field using the results of a $.getJSON() request. All of the return values have the same key as the name attribute of the form field they belong to.
Naturally, I tried to use .val("foo") to deal with cross-browser/field type discrepancies but it wouldn't work. Oddly, .attr("value","foo") does.
Any ideas? Is this expected behavior, or an undocumented quirk? Here is the relevant code snippet:
function showSites(){
$.getJSON("process.php?action=showSites", function(data) {
var items = [];
$.each(data.sites, function(key, val) {
var $form = $("#addSiteForm").clone();
var buttons = '<button id="getCert" class="button" href="getCert.php?id=' + val.id + '">Get Cert</button>'
+ '<button id="updateSite" class="button" href="process.php?action=updateSite&id=' + val.id + '">Update Site</button>'
+ '<button id="deleteSite" class="button" href="process.php?action=deleteSite&id=' + val.id + '">Delete Site</button>';
// set siteId
$form.find("input[name=siteId]").attr("value",val.id);
// change values
$.each(val, function(i,v){
$form.find("[name="+i+"]").val(v);
});
items.push('<h3>' + val.name + '</h3>');
items.push("<div class='site'>");
items.push("<form class='siteForm' id='"+val.id+"'>");
items.push($form.html());
items.push("</form>");
items.push(buttons);
items.push("</div>");
});
var foo = items.join('');
$("#sites").prepend(foo).accordion("destroy").accordion();
});
});
You can use .val() property in input tags( text box, textarea,..) only.
attr("attrname","value") this is used to set value to any tags. You can set some dummy attr in div tag and retrieve value attr("attrname");

Categories

Resources