I want the select name array keys have a quotations inside. But this one doesn't generate quotations inside the brackets. How can I achieve it?
var id = "test";
var element = "<select name = 'unit_id["+id+"]' class = 'form-control'></select>";
You can use Template literals which is more cleaner. This does not require string concatenation and character escaping:
var id = "test";
var element = `<select name = 'unit_id["${id}"]' class = 'form-control'></select>`;
console.log(element)
Like this:
var id = "test";
var elemnt = "<select name=\"unit_id['" + id + "']\" class=\"form-control\"></select>";
Related
I have a string which looks like this: (id:561644cdb40fbe0100247dd7:q) (id:56165d8a79c8c40100adbdb6:q) and I need to replace the different id's with different values. I already have the id's in a variable and trying to loop through with something like this var mailId = "(id:" + rplcId + ":q)"; But If I use the replace() function it doesnt work...Any other suggestions?
You can select the id with:
"(id:56165d8a79c8c40100adbdb6:q)".split(":")[1]
var id = "(id:561644cdb40fbe0100247dd7:q)";
var idArr = id.split(":");
idArr[1] = newId; //56165d8a79c8c40100adbdb6
var mailId = idArr[0]+idArr[1]+idArr[2];
and please provide your full code
VIEW
$1 = array('value'=>'1|3','class'=>'temp_stok', 'id'=>'st1');
$2 = array('value'=>'2','class'=>'temp_stok','id'=>'st2');
$3 = array('value'=>'5|7','class'=>'temp_stok','id'=>'st3');
echo form_input($1);echo form_input($2); echo form_input($3);
i want to split every value content '|'
var id = $('.temp_stok').id();
var val_id = $('#st'+id).val();
if(val_id.indexOf('|') >= 1)
{ var _stok = val_id.split('|');
var stok1 = _stok[0]; var stok1 = _stok[1]; }
but the problem is get the id. How can i get id ?
You may try something like this (Example):
// Select all inputs that contains | in it's value
var inputsWithPipe = $("input[value*='|']");
// Then loop all the inputs and split
$.each(inputsWithPipe, function(k, v){
var arr = v.value.split('|');
console.log(arr); // an array of numbers
});
Now you may use each arr array as you want.
Try this to get the id of the element you are interested in:
var id = $('.temp_stok').attr('id');
I have a combobox in HTML:
<select id="dimensionName"><option>/Example.html</option></select>.
In my JavaScript, if I have a var URL1 = "facebook.com", and I want to append the selected string from the above combobox to the end of URL1, and set the appended string as a new variable as NewDimensionName, how can I do that?
I tried doing the following but to no avail:
var NewDimensionName = URL1.concat(document.getElementById("dimensionName").selectedItem);
Since you want to get the text, you would have to do it like this:
var x = document.getElementById("dimensionName");
var NewDimensionName = URL1+x.options[x.selectedIndex].text;
This gets the options array with the selected index and returns the text, not the value.
Also note that concat() is used for arrays, not strings. Simply using + will suffice here.
Can you try this,
var dimensionName= document.getElementById("dimensionName");
var dimensionText= dimensionName.options[dimensionName.selectedIndex].text;
var NewDimensionName = URL1 + dimensionText;
console.log("NewDimensionName ::" + NewDimensionName );
x = document.getElementById("dimensionName").options[dimensionName.selectedIndex].innerHTML;
x = URL1 + x;
alert x;
I obtain some CSS and store it in a var, but i am trying to use regexes to parse classes. Thats the easy part, but it seems that i have issues with the regex to scrape contents between the braces to store.
My attempt is at: http://jsfiddle.net/2qaCY/
All i want is to iteratively loop through the classes and scrape the contents between the braces.
code on fiddle:
var css = ".Winning{color: #24CCFF;background-color: #FF8091;}.Losing{color: #2EFFCE;background-color: #DB4DFF;}.crayons{font-family: papyrus;font-size: 32pt;}";
var reg = /\.[a-zA-Z0-9]*\{/ig;
var matches = css.match(reg);
for (var m in matches) {
var sClass = matches[m].substr(0, matches[m].length - 1);
$("body").append(sClass + "<br />");
var c = new RegExp("\\." + sClass + "[\\n\\s]*\{[\\s\\n.]*\}", "ig");
var out = c.exec(css);
$("body").append(out);
$("body").append("<br /><br />");
}
Ok, so the following example stores the class in an array and the whole thing in a map where the key is the class and the contents are the value for that key.
If you want a solution with regexp it's 10 more minutes but this is what you want I believe.
http://jsfiddle.net/2qaCY/11/
var css = ".Winning{color: #24CCFF;background-color: #FF8091;}.Losing{color: #2EFFCE;background-color: #DB4DFF;}.crayons{font-family: papyrus;font-size: 32pt;}";
var reg = /\.[a-zA-Z0-9]*\{[a-zA-Z0-9:\- #;]+\}/ig;
var matches = css.match(reg);
var classes = []
var classMap = {}
matches.map(function(item) {
var cl = (item.split("{")[0])
classes.push(cl)
classMap[cl] = item.split("{")[1].split("}")[0]
})
// All the classes in an array
console.log(classes);
console.log(classMap);
I am trying to pull the attributes out of piece of submitted text in Javascript and change it to an array.
So the user submits this:
<iframe src="http://www.stackoverflow.com/" width="123" height="123" frameborder="1"></iframe>
and I would get:
arr['src'] = http://www.stackoverflow.com/
arr['width'] = 123
arr['height'] = 123
arr['frameborder'] = 1
Just need a regexp I think but any help would be great!
I recommend to use a RegExp to parse user-inputed HTML, instead of creating a DOM object, because it's not desired to load external content (iframe, script, link, style, object, ...) when performing a "simple" task such as getting attribute values of a HTML string.
Using similar (although similarcontradiction?) methods as in my previous answer, I've created a function to match quoted attribute values. Both quoted, as non-quoted attributes are matched.
The code currently returns an object with attributes from the first tag, but it's easily extensible to retrieve all HTML elements (see bottom of answer).
Fiddle: http://jsfiddle.net/BP4nF/1/
// Example:
var htmlString = '<iframe src="http://www.stackoverflow.com/" width="123" height="123" frameborder="1" non-quoted=test></iframe>';
var arr = parseHTMLTag(htmlString);
//arr is the desired object. An easy method to verify:
alert(JSON.stringify(arr));
function parseHTMLTag(htmlString){
var tagPattern = /<[a-z]\S*(?:[^<>"']*(?:"[^"]*"|'[^']*'))*?[^<>]*(?:>|(?=<))/i;
var attPattern = /([-a-z0-9:._]+)\s*=(?:\s*(["'])((?:[^"']+|(?!\2).)*)\2|([^><\s]+))/ig;
// 1 = attribute, 2 = quote, 3 = value, 4=non-quoted value (either 3 or 4)
var tag = htmlString.match(tagPattern);
var attributes = {};
if(tag){ //If there's a tag match
tag = tag[0]; //Match the whole tag
var match;
while((match = attPattern.exec(tag)) !== null){
//match[1] = attribute, match[3] = value, match[4] = non-quoted value
attributes[match[1]] = match[3] || match[4];
}
}
return attributes;
}
The output of the example is equivalent to:
var arr = {
"src": "http://www.stackoverflow.com/",
"width": "123",
"height": "123",
"frameborder": "1",
"non-quoted": "test"
};
Extra: Modifying the function to get multiple matches (only showing code to update)
function parseHTMLTags(htmlString){
var tagPattern = /<([a-z]\S*)(?:[^<>"']*(?:"[^"]*"|'[^']*'))*?[^<>]*(?:>|(?=<))/ig;
// 1 = tag name
var attPattern = /([-a-z0-9:._]+)\s*=(?:\s*(["'])((?:[^"']+|(?!\2).)*)\2|([^><\s]+))/ig;
// 1 = attribute, 2 = quote, 3 = value, 4=non-quoted value (either 3 or 4)
var htmlObject = [];
var tag, match, attributes;
while(tag = tagPattern.exec(htmlString)){
attributes = {};
while(match = attPattern.exec(tag)){
attributes[match[1]] = match[3] || match[4];
}
htmlObject.push({
tagName: tag[1],
attributes: attributes
});
}
return htmlObject; //Array of all HTML elements
}
Assuming you're doing this client side, you're better off not using RegExp, but using the DOM:
var tmp = document.createElement("div");
tmp.innerHTML = userStr;
tmp = tmp.firstChild;
console.log(tmp.src);
console.log(tmp.width);
console.log(tmp.height);
console.log(tmp.frameBorder);
Just make sure you don't add the created element to the document without sanitizing it first. You might also need to loop over the created nodes until you get to an element node.
Assuming they will always enter an HTML element you could parse it and read the elements from the DOM, like so (untested):
var getAttributes = function(str) {
var a={}, div=document.createElement("div");
div.innerHTML = str;
var attrs=div.firstChild.attributes, len=attrs.length, i;
for (i=0; i<len; i++) {
a[attrs[i].nodeName] = attrs[i].nodeValue];
}
return a;
};
var x = getAttributes(inputStr);
x; // => {width:'123', height:123, src:'http://...', ...}
Instead of regexp, use pure JavaScript:
Grab iframe element:
var iframe = document.getElementsByTagName('iframe')[0];
and then access its properties using:
var arr = {
src : iframe.src,
width : iframe.width,
height : iframe.height,
frameborder : iframe.frameborder
};
I would personally do this with jQuery, if possible. With it, you can create a DOM element without actually injecting it into your page and creating a potential security hazard.
var userTxt = '<iframe src="http://www.stackoverflow.com/" width="123" height="123" frameborder="1"></iframe>';
var userInput = $(userTxt);
console.log(userInput.attr('src'));
console.log(userInput.attr('width'));
console.log(userInput.attr('height'));
console.log(userInput.attr('frameborder'));