replace in jQuery
Can some one help me in this
I had a variable
var myValue = "what is you name? what is your age?"
i 开发者_开发技巧want to find the '?' in the string and replace it with a html input text element
where the user can enter the answer in the text box and at last i need a string as out put like this
"what is your name my name is xyz what is your age i am 25"
Please help me in this
Thanks Kumar
This will dynamically take your myValue, replace all ?'s with inputs and then add a button to alert you of the user input. It will place myValue into the body, but you can place it somewhere else.
$(function() {
var myValue = "what is you name? what is your age?";
myValue = "<div>" + myValue;
while(myValue.indexOf("?") > -1)
myValue = myValue.replace("?", " <input type=\"text\" />");
myValue += "</div>" + "<button type=\"button\" onclick=\"sumUp(this)\">Declare</button>";
$("body").html(myValue);
});
function sumUp(button) {
var $prevDiv = $(button).prev().clone();
$prevDiv.children("input").each(function() {
$(this).replaceWith($(this).val());
});
alert($prevDiv.html());
}
If you have 2 input elements with IDs 'name' and 'age' respectively you can do this:
var nameValue = document.getElementById('name').value;
var ageValue = document.getElementById('age').value;
var anotherValue = myValue
.replace(/name\?/, nameValue)
.replace(/age\?/, ageValue)
You should be able to do something as simple as:
var myValue = "what is you name? what is your age?"
var nameVar = window.prompt("What is your name?","");
var ageVar = window.prompt("What is your age?","");
var myValue = myValue.replace("?", nameVar).replace("?", ageVar);
Alternatively, you could do something like:
var myValue = "what is you name? what is your age?"
var nameVar = '<input type="text" id="name" name="name">';
var ageVar = '<input type="text" id="age" name="age">';
document.write(myValue.replace("?", nameVar).replace("?", ageVar))
You'd then read the two input elements using jQuery with:
$('name').val();
$('age').val();
If you have a div with the question in it:
<div id="questions">What is your name? What is your age?</div>
and you want to replace those ? marks with input boxes, you could do this to make input boxes show up right after the questions:
var questions = $("#questions").text();
var questionMarkIndex = questions.indexOf("?");
var nameQuestion = questions.substring(0, questionMarkIndex+1);
var finalHtml = nameQuestion + '<input id="name" type="text" />';
var ageQuestion = questions.substring(questionMarkIndex+1);
finalHtml += ageQuestion + '<input id="age" type="text" />';
$("#questions").html(finalHtml);
This (or something close to it) will make you end up with What is your name?[input box] What is your age?[input box]
.
精彩评论