I have some js that adds an input field for a user:
var user = "O'Conner, John"
b.innerHTML += "<input type='hidden' value='" + user + "'>";
When its inserted it looks like this:
<input type="hidden" value="O" Conner, John'>
How do I amend this so it outputs like this:
<input type="hidden" value="O'Conner, John">
I need the value to show the full name with the apostrophe. How can I get this to work?
You can escape the value first by replacing it with HTML entities.
As for ' - It can either be ’ or ‘
var user = "O'Conner, John";
user = user.replace("'", "‘");
document.getElementById("container").innerHTML += "<input type='text' value='" + user + "'>";
<div id="container"></div>
There is also another thread that already answers this question.
When you create an element with JavaScript, you can pass the value to the input without any issue. Please check the below example:
var user = "O'Conner, John"
var b = document.getElementById("b")
var input = document.createElement("input")
input.type = "text"
input.value = user;
b.appendChild(input)
<body id="b"></body>
Related
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 ) );
});
});
I have an app for making questionnaires. Users have index.php page where they create the questions and choose minimum number of answers, then they have process.php page where they can enter their answers or add more answers.
PROBLEM: When user clicks add more button, it creates textarea of the particular question but with the wrong name. The add more button should add a textarea and change its name according to the minimum of the defined textareas. So if you for ex. have 4 defined textareas in question2, the next textareas should be like odg25, odg26, odg27, odg28 etc...
The problem is in variable $k (process.php) - because it is not defined in addmore function, but I don't know how to pass somehow in this part of code to make it happen.
THIS IS THE TESTING LINK
INDEX.PHP
<input id="btntxt" type="submit" value="TEXT" onclick="addtxt();" /><br/><br/>
<form action="process.php" method="post">
Title: <br/><input type="text" name="naslov" size="64" required ><br/>
Maximum characters: <br/><input type="text" name="chars" size="64"><br/><br/>
<div id="brain1"></div><br/>
<input type="submit" name="submit" value="CONFIRM"><br/>
</form>
PROCESS.PHP
<script type="text/javascript">
<?php $chars = $_POST['chars']; ?>
function addmore(index) {
var textarea = document.createElement("textarea");
textarea.name = "odg" + index + //WHAT SHOULD I ADD HERE???;
textarea.rows = 3;
textarea.setAttribute('maxlength',<?php echo $chars ?>);
var div = document.createElement("div");
div.innerHTML = textarea.outerHTML;
document.getElementById("inner"+index).appendChild(div);
}
</script>
<body>
<?php
$bla = "";
$pitanje = $_POST['question'];
$length = count($_POST['question']);
$req = $_POST['req'];
$requiem = '';
$min = $_POST['min'];
$area = array("","","","","","","","","","","","","","","");
for($j=1; $j<$length+1; $j++) {
if($_POST['question'][$j] != "") {
if(($min[$j])!="") {
for($k=1;$k<=$min[$j];$k++) {
$area[$j] .= '<textarea name="odg'.$j.$k.'" rows="3"'.$requiem.' maxlength="'.$chars.'" ></textarea><br/>';}}
if(($min[$j])=="") {
$area[$j] = '<textarea name="odg'.$j.$k.'" rows="3"'.$requiem.' maxlength="'.$chars.'" ></textarea>';}
$addmore = '<input type="button" name="more" value="Add more" onClick="addmore('.$j.');">';
$bla .= $j.') '.$pitanje[$j].'<br/>'.$area[$j].'<div id="inner'.$j.'"></div>'.$addmore.'<br/>';}}
echo $bla;
?>
FNCS.JS
var n = 1;
function addtxt() {
var textarea = document.createElement("textarea");
textarea.name = "question[" + n + "]";
var required = document.createElement("input");
required.type = "checkbox";
required.name = "req[" + n + "]";
var minimum = document.createElement("input");
minimum.type = "text";
minimum.name = "min[" + n + "]";
var div = document.createElement("div");
div.innerHTML = n + ". Question: " + "<br />" + textarea.outerHTML + "<br />" + "Required: " + required.outerHTML + "<br />" + "Min: " + minimum.outerHTML + "<br /><hr/><br/>";
document.getElementById("brain1").appendChild(div);
n++;
}
I did the same kind of dev.
I had a globalized counter (cpt) in the javascript is incremented by 1 each duplication
My variables were duplicated like this id = "foo_" + cpt.
I added a hidden field for the counter <input type="hidden" id = "cpt"> and its value was changed for each replication.
Php side, I recovered the counter and then a loop to iterate through all the duplicate fields.
// For example
$cpt = $_POST['cpt'];
for ($i = 1; $i <= $cpt; $i++) {
$foo[$i] = $_POST['foo_' . $i];
}
I hope it will help.
You're mixing JavaScript and PHP. PHP is doing some part of the question generation and then JavaScript has to pick up where it left off.
The problem with that approach is that you'll find you end up duplicating a lot of functionality.
The answer the quesiton WHAT SHOULD I ADD HERE??? is "odg" + $j + $k
If instead you start by doing:
var questions = <?php echo json_encode($_POST["question"]);?>;
You now have all your question data available in JavaScript. You can move the for loop from PHP to JavaScript and have j and k there.
What you're going to have to do is make $k able to be passed into process.php.
That is accomplished with something like this:
<form action="process.php" method="post">
Title: <br/><input type="text" name="naslov" size="64" required ><br/>
Maximum characters: <br/><input type="text" name="chars" size="64"><br/><br/>
<div id="brain1"></div><br/>
<input id="numRows" type="hidden" name="numRows" value="1"/>
<input type="submit" name="submit" value="CONFIRM"><br/>
</form>
notice I've added a new <input> element with the name "numRows" which will be passed via POST to process.php. I've given it an arbitrary default value of 1, you can set this however you wish.
Now, when a user clicks the "add more" button, within fncs.js do this:
document.getElementById("numRows").value++;
and finally, in your process.php you need to read in the value of this, as $k:
<?php $k = isset($_POST['numRows']) ? urldecode($_POST['numRows']) : 1; ?>
within process.php you may do as you wish, then, with that value $k.
You need to store last text area value in hidden variable and always increment that
first step: At start set value of hidden variable and your counter
'n' same
second step : at each step where you are adding new text area ,
overwrite the hidden value by new counter value of text area
Remember Textarea counter should be always fetched from hidden value
I think this may help you to solve your problem
I used the below code to produce input in run time . Alert shows correctly but append causes mistake and meanwhile the single and double quotation will be changed.
Var name1=$(a).attr ('name');
Var idimg=name1+"z";
Var nedi="<input type='file' name='zozo' onchange ='readURL(this , '" + idimg + "');' />";
$(nedi).appendTo ("#divv");
In run time its like :
<input type ="file" name ="zozo" onchange="readURL (this , "3z' ) ; '>
Your code should look like that:
var name1 = $(a).attr('name');
var idimg = name1 + "z";
var nedi = "<input type='file' name='zozo' onchange ='readURL(this , \"" + idimg + "\");' />";
$(nedi).appendTo("#divv");
I.e. you should escape and use double quotes in onchange attribute.
I want the variable inputname to go up by 1 every time a new <input /> is added
e.g.
<input name="1" />
<input name="2" />
<input name="3" />
---html---
<p class="add">Add</p>
<div class="added"></div>
---jQuery/javascript---
$(document).ready(function() {
$("p.add").click(function() {
var inputname = somevar;
var added = "<input type=\"text\" name=\""+inputname+"\" />";
$("div.added").append(added);
});
});
here it is on jsfiddle.net if it helps -> http://jsfiddle.net/gamepreneur/54kzw/
Set inputname like this:
var inputname = $('.added input').length + 1;
This gets the total number of added inputs and increments by one, resulting in the new name.
Change the variable scope
Use this:
// declare your variable here so it exists throughout every call, instead of being
// delcared new with every call.
var inputname = somevar;
$(document).ready(function() {
$("p.add").click(function() {
var added = "<input type=\"text\" name=\""+(inputname++)+"\" />";
$("div.added").append(added);
});
});
Alternatives:
Grab the number of inputs ($('div.added input').length) and use that for a counter.
Grab the id of the last item $('div.added input:last').prop('name')) and increment it.
You need to declare inputname in the global scope so that it lasts longer than just the duration of the click function and then you need to increment it each time you use it.
I modified your fiddle to this: http://jsfiddle.net/jfriend00/54kzw/2/
var inputname = 1;
$(document).ready(function() {
$("p.add").click(function() {
var added = "<input type='text' name='" + inputname++ + "' />";
$("div.added").append(added);
});
});
Try
$(document).ready(function() {
$("p.add").click(function() {
var inputname = $('input', $("div.added")).length + 1;
var added = "<input type=\"text\" name=\"" + inputname + "\" />";
$("div.added").append(added);
});
});
Consider adding some other selectors to choose those inputs (like a class selector)
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].