All,
I have the following html as a string in javascript. I need to extract the string in "value", split by the specified delimeter "|" and put in two variables.
var html = '<div><input name="radBtn" class="radClass" style="margin:auto;"
onclick="doSomething();"
value="Apples|4567" type="radio">
</div>';
Required output is two variables having the following values:
fruitName = Apples
fruitNumber = 4567
Note: There can be many radio buttons with the same name.
All,
I have the following html as a string in javascript. I need to extract the string in "value", split by the specified delimeter "|" and put in two variables.
var html = '<div><input name="radBtn" class="radClass" style="margin:auto;"
onclick="doSomething();"
value="Apples|4567" type="radio">
</div>';
Required output is two variables having the following values:
fruitName = Apples
fruitNumber = 4567
Note: There can be many radio buttons with the same name.
Share Improve this question asked Apr 27, 2011 at 20:52 JakeJake 26.1k31 gold badges114 silver badges177 bronze badges 1- 1 Everyone answering in this thread is not reading the problem. It's not HTML, it's a string. – wdm Commented Apr 27, 2011 at 21:02
6 Answers
Reset to default 9If you can assume that your HTML is always going to be simple (i.e. only one value attribute, and nothing else that looks like a value attribute), then you can do something like this:
var fruit = html.match(/value="(.*?)\|(.*?)"/);
if (fruit) {
fruitName = fruit[1];
fruitValue = fruit[2];
}
Here's how you can do it:
$("input[name='radBtn']").click(function(){
var val = $(this).val();
val = val.split("|");
var fruit = val[0];
var number = val[1];
});
var div = document.createElement("div");
div.innerHTML = '<input name="radBtn" class="radClass" style="margin:auto;" onclick="doSomething();" value="Apples|4567" type="radio"></div>';
var str = div.getElementsByTagName("input")[0].split("|");
var fruitName = str[0];
var fruitNumber = str[1];
/*
Now,
fruitName = "Apples"
and
fruitNumber = 4567
*/
Here's one way:
var fruit = (function() {
var fruits = $(html).find('.radClass').val().split('|');
return {
fruitName: fruits[0],
fruitNumber: fruits[1]
};
}());
You'll get an object like this:
fruit.fruitName // Apples
fruit.fruitNumber // 4567
var coolVar = '123-abc-itchy-knee';
var partsArray = coolVar.split('-');
// Will result in partsArray[0] == '123', partsArray[1] == 'abc', etc
see: How to parse a string in javascript?
$(function() {
$("INPUT[name=radBtn]").click(function() {
var value = $(this).val().split("|");
var fruitName = value[0];
var fruitNumber = value[1];
// Add to an array, ajax post etc. whatever you want to do with the data here
});
});