Edit attribute value in an HTML string - javascript

So, I've got a string. The string contains html. I'm checking the string for 'name', if it doesn't have one I'm using sneaking one in there if it does I need to change what it is.
var myString = '<input id="accountUser_c967817c993e62b1de50e4f0401a03ae" type="hidden" value="c967817c993e62b1de50e4f0401a03ae" name="addRow[]"><div class="colors goldbluegreenorange"></div>';
if (myString.indexOf('name') == -1) {
myString = myString.substr(0,myString.indexOf('>')) + ' name="addRow[]"' + myString.substr(myString.indexOf('>'));
} else {
//get what's inside name's quotes and change it to removeRow[].
}
I've got jquery going on too, if that makes more sense than straight javascript.

Since you're using jQuery, why not create a jQuery element out of that string, so that we can use jQuery's beautiful API for this? It'll make it far less error-prone than raw string manipulation.
Here's some sample code:
var $element = $('<input id="accountUser_c967817c993e62b1de50e4f0401a03ae" type="hidden" value="c967817c993e62b1de50e4f0401a03ae" name="addRow[]"><div class="colors goldbluegreenorange"></div>');
$element.filter('input').prop('name', function(i, v) {
return v ? 'removeRow[]' : 'addRow[]';
});
Note: the v in that function is the current value of the name attribute, which jQuery automatically passes in to the callback function. The return value is what the value of the attribute should be updated to.
Update: If you then want to convert it all back into a string, use this:
var theHTMLstring = $element.wrapAll('<div>').parent().html();
Here's the fiddle: http://jsfiddle.net/kBF3c/

Try converting the string to a jQuery object and reading the parameter from that:
var myString = '<input id="accountUser_c967817c993e62b1de50e4f0401a03ae" type="hidden" value="c967817c993e62b1de50e4f0401a03ae" name="addRow[]"><div class="colors goldbluegreenorange"></div>';
var $input = $(myString).filter('input');
$input.attr('name') = ($input.attr('name') == "") ? 'addRow[]' : 'removeRow[]';

Since you're using jQuery anyways, why don't you just parse the string and treat the tags as HTML?
var html = $.parseXML(string);
$.each(html.find('*'),function()
{
if ($(this).attr('name'))
{
$(this).attr('name', 'addRow[]');
}
else
{
$(this).attr('name','removeRow[]');
}
});
And take things from there?

Why don't you just use jQuery's inbuilt functionality.
Demo here
// specify string representing input element
var str = '<input id="accountUser_c967817c993e62b1de50e4f0401a03ae" type="hidden" value="c967817c993e62b1de50e4f0401a03ae" name="addRow[]"><div class="colors goldbluegreenorange"></div>';
var els = $(str);
// create element
var el = $(els).filter("input");
if( $(el).prop("name") ) {
$(el).prop( "name", "removeRow[]" );
} else {
$(el).prop("name", "anynameyouwant");​​​​​​​​​​​​​​
}
I am guessing you need to add the the above elements to the DOM which you can do like so
$("#parentId").append( els );

You may try this
var str = '<input id="accountUser_c967817c993e62b1de50e4f0401a03ae" type="hidden" value="c967817c993e62b1de50e4f0401a03ae" name="addRow[]"><div class="colors goldbluegreenorange"></div>';
$(str).prop('name', (!$(str).prop('name') ? "addRow[]" : "removeRow[]"));
str=$('<div/>').html(obj).html(); // str contains new value
DEMO.

Related

Sanitizing input to stick into a hidden input value with jQuery

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"

Remove all tags in html string except <a>

I'v got some html which I must clear from all tags except one concrete <a> with known class.
Here is the html:
var string = '<span class="so_sentence"><span> Some text <a class="so_footnote-ref" href="#footnote-104008-4" id="footnote-104008-4-backlink">[1]</a></span></span>';
I have JQuery attached, so I get the jQuery object of the string.
var html = $(string);
Now I have to clear the string from all the span and probably other tags, except this <a>:
<a class="so_footnote-ref" href="#footnote-104008-4" id="footnote-104008-4-backlink">[1]</a>
So my final string should be:
'Some text <a class="so_footnote-ref" href="#footnote-104008-4" id="footnote-104008-4-backlink">[1]</a>'
Also it must be possible to call this function on the result, so it must be of appropriate type:
function _trim(string){
return string.replace(/(?:(?:^|\n)\s+|\s+(?:$|\n))/g,'').replace(/\s+/g,' ');
}
Try this:
$(string).find(':not(a)').contents().unwrap()
This will vorky with every piece of html code.
Example: http://jsfiddle.net/E3RWL/1/
Here's a function I found for you:
You can read more about this at: http://phpjs.org/functions/strip_tags/
Javascript:
var ret = strip_tags('<p>Kevin</p> <br /><b>van</b> <i>Zonneveld</i>', '<i><b>');
// returns: 'Kevin <b>van</b> <i>Zonneveld</i>'
function strip_tags (input, allowed) {
allowed = (((allowed || "") + "").toLowerCase().match(/<[a-z][a-z0-9]*>/g) || []).join(''); // making sure the allowed arg is a string containing only tags in lowercase (<a><b><c>)
var tags = /<\/?([a-z][a-z0-9]*)\b[^>]*>/gi,
commentsAndPhpTags = /<!--[\s\S]*?-->|<\?(?:php)?[\s\S]*?\?>/gi;
return input.replace(commentsAndPhpTags, '').replace(tags, function ($0, $1) {
return allowed.indexOf('<' + $1.toLowerCase() + '>') > -1 ? $0 : '';
});
}

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

Print dynamic Text box value using JQuery

I have a scenario like
for(int i = 0; i < 10; i++)
{
<input type = "text" id="test"+i value="" onchange="getValue(i)">
}
I want to print selected text box value using jquery. I tried below code,....
function getValue(id)
{
var value = $("#test"+id).val();
alert(value);
}
Some how the above code is not working.
if i tried like var value = document.getElementById("test"+id); then it is working.
jsBin demo
var inp = ''; // String will hold all inputs
for(var i=0; i<10; i++){
inp += '<input type="text" id="test'+i+'" value="" />'; // Generate 10 inputs
}
$('body').append( inp ); // All inputs to HTML
$('input[id^="test"]').on('input', function(){
console.log( this.value );
});
You can't just drop raw HTML inside of a JavaScript loop like that. You have to set a string or create an element and append it to the DOM.
"getValue(i)" is a string. The "i" is not the variable i, it is literally a string with the letter i. If you want to concatenate strings and variables you have to do so like this:
var name = "Neil";
var greeting = "Hi, my name is " + name + ", nice to meet you!";

Get array of values from multiple inputs using jQuery

Can someone please let me know how to get values from several input fields?
I have a list with several inputs like this:
<li>
<label>Additional Title: </label><input type='text' name='additionaltitlename' ... />
</li>
<li>
<label>Additional Title: </label><input type='text' name='additionaltitlename' ... />
</li>
I have a solution in Javascript (on form submit):
...
var extratitles = document.getElementsByName('additionaltitlename');
var str = '';
for (var i = 0; i < extratitles.length; i++) {
str = str + '|' + extratitles.item(i).value;
}
}
How do I do the same thing in JQuery?
It's not valid to have two inputs of the same name. If you want to do this, you can use <input name="titles[]">
You can try this:
<input name="titles[]">
<input name="titles[]">
​<button>submit</button>​​​​​​​​​​​​​​​​​​​​​​​
With this jQuery
// click handler
function onClick(event) {
var titles = $('input[name^=titles]').map(function(idx, elem) {
return $(elem).val();
}).get();
console.log(titles);
event.preventDefault();
}
// attach button click listener on dom ready
$(function() {
$('button').click(onClick);
});
See it working here on jsFiddle
EDIT
This answer gives you the titles in an array instead of a string using a | separator. Personally, I think this is a lot more usable.
If you're just submitting the form and you want to support multiple values, use the .serialize method as described in the other answer
Use jQuery's native serialize function:
var data = $('input[name="additionaltitlename"]').serialize();
docs
The .serialize() method creates a text string in standard URL-encoded notation. It operates on a jQuery object representing a set of form elements.
It is very easy in jquery. you can do this as:
types = [];
$("input[name='additionaltitlename']").each(function() {
types.push($(this).val());
});
console.log(types);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="additionaltitlename1" name="additionaltitlename" class="form-control" value="abc">
<input type="text" id="additionaltitlename2" name="additionaltitlename" class="form-control" value="xyz">
In addition to #gdoron's or #macek's answer which are probably the way to go, I'd like to add that all that is wrong with the code you have posted is that you have one } too much. This works (although it still has room for improvement):
$('#getpreviewbutton').click(function(){
var extratitles = document.getElementsByName('additionaltitlename');
var str = '';
for (var i = 0; i < extratitles.length; i++) {
str = str + '|' + extratitles.item(i).value;
}
});​
See: http://jsfiddle.net/8XJcc/
I don't know which browser you are using but using sth like Firebug or the Chrome Dev Tools can be pretty handy to spot simple mistakes like this. See this reference for Chrome or this one for Firefox. Even IE has one - just press F12.
Means:
str = '';
$("input[type='text']").each(function() {
str = str + '|' + $(this).val();
});
or
str = '';
$("input[name='additionaltitlename']").each(function() {
str = str + '|' + $(this).val();
});
?

Categories

Resources