How to programmatically escape quotes? [duplicate] - javascript

This question already has answers here:
Escape quotes in JavaScript
(13 answers)
Closed 8 years ago.
this should be simple but I can't figure it out.
I want to let user edit a value. To do so, upon click, the value changes into a textbox. However, if the user puts a quote mark in the user input within the text box the value="" attribute of the text box closes prematurely and the quote mark and anything after it gets lost. Escape (deprecated) and encodeURI merely replace the quote mark with asci does which don't look good in the textbox.
Would appreciate anyone's solution to this problem:
Here is javascript:
function editText() {
var text = document.getElementById('text').innerHTML;
var edittext = '<input type="text" size=60 name="name" id="name" value="'+text+'"><input type="button" value="Save" onclick="storeText(\'name\');">';
document.getElementById('text').innerHTML = edittext
return false;
}
html:
Text: <span id="text" onclick="editText()";>He said "that's cool"</span>
jsfiddle
http://jsfiddle.net/2s9v2/6/
UPDATE:
Contrary to what those who marked this as a duplicate say, the duplicate question does not provide an answer to my question. They might want to re-read my question and the so-called duplicate and mentally register the word "programmatic" in my question and actually look at the code in the duplicate relaive to the code here.... Just saying.
I ended up changing the textbox to a textarea as a workaround as there does not seem to be a straightfoward way to programmatically escape a quote within a textbox.
The answer from Merlin below is a possible approach but calling the second function is more complex than just replacing textbox with textarea. In any case, I could not get that to work but I thank Merlin for his answer and upvoted it.

Try: text.replace(/"/g,""")
Ideally, though, you should be creating the elements with createElement, at which point you can do elem.value = text with no need for escaping.

Why not just set the value directly instead of rebuilding the input?
document.getElementById('name').value = edittext
Of course, this assumes that the input element with id=name already exists in your DOM, but I see no particular reason you could not ensure that it is already there (either writing directly in HTML or generating in Javascript on page load).
Update: It seems that the OP wants the element to be dynamically created in the onClick, by turning the text that is currently in a div into an input field with the contents of that div as its value.
I believe the following might do the trick, assuming id is unique as it should be.
function editText() {
var text = document.getElementById('text').innerHTML;
var edittext = '<input type="text" size=60 name="name" id="name" value="" /><input type="button" value="Save" onclick="storeText(\'name\');">';
document.getElementById('text').innerHTML = edittext;
document.getElementById('name').value = text;
document.getElementById('text').onclick = function() {}; //
return false;
}
Note that you will need to disable the onClick inside the above function as well, and then re-enable it inside storeText, because otherwise every click will cause extra buttons to be added.
Update 2: Here is a fully working example without parameter passing (for simplicity).
<html>
<body>
<script>
function editText() {
var text = document.getElementById('text').innerHTML;
var edittext = '<input type="text" size=60 name="name" id="name" value="" /><input type="button" value="Save" onclick="storeText();">';
document.getElementById('text').innerHTML = edittext;
document.getElementById('name').value = text;
document.getElementById('text').onclick = function() {};
return false;
}
function storeText() {
document.getElementById('text').innerHTML = document.getElementById('name').value;
document.getElementById('text').onclick = "editText();";
}
</script>
<div id="text" onclick="editText();">HelloWorld</div>
</body>
</html>

Related

Adding a textbox to div without losing values [duplicate]

This question already has answers here:
InnerHTML append instead of replacing
(3 answers)
Closed 6 years ago.
i've a div container and a button. Whenever i click the button, an empty textbox is added to the div. Now, my problem is whenever i click the button, the textbox is added, but the values of all others are removed.
The function is made like this:
function addTextBox() {
document.getElementById("txtList").innerHTML += "<input type='text'>";
}
I think it help you:
var child = document.createElement('input')
document.getElementById("txtList").appendChild(child);
You could achieve the same thing as the snippet below:
function addTextBox() {
var input = document.createElement("input");
input.type = "text"
document.getElementById("txtList").appendChild(input);
}
document.getElementById("addTxtBoxBtn").addEventListener("click",addTextBox);
<input type="button" id="addTxtBoxBtn" value="add TextBox"/>
<div id="txtList">
</div>
Why you can't achieve the same thing with innerHTML?
This happens because:
The Element.innerHTML property sets or gets the HTML syntax describing the element's descendants.
While the valueof an ipunt element is not an attribute of the element but a property (please have a look here).
If you want to check it in action, please try the following snippet:
function addTextBox() {
var txtList = document.getElementById("txtList");
console.log(txtList.innerHTML);
txtList.innerHTML += "<input type='text'/>" ;
}
document.getElementById("addTxtBoxBtn").addEventListener("click",addTextBox);
<input type="button" id="addTxtBoxBtn" value="add TextBox"/>
<div id="txtList">
</div>
What is happening under the hood here is that when you append the DOM as text using innerHTML you are simply rewriting that section of HTML. Editing your textList innerHTML will execute a new paint of that element and all information will be parsed again. This means you loose your user interaction.
To update your DOM elements successfully there are methods which enable you to do that. namely document.createElement and document.appendChild.
By appending the DOM element as opposed to concatenating the innerHTML(text) your are forcing a limited paint of the specific area. This leaves the rest of the DOM in tact.
Your code here
function addTextBox() {
document.getElementById("txtList").innerHTML += "<input type='text'>";
}
Becomes more like the following
function addTextBox() {
var textEl = document.getElementById("txtList");
var input = document.createElement("input");
input.type = 'text';
textEl.appendChild(input);
}
When you change append to innerHTML as a string, another string gets created (they are immutable). Browser than has to re-render the whole thing.
The other answers show appendChild, but since in your original question you used a string, maybe you want to keep doing so. If that's the case, you can use insertAdjacentHTML with 'beforeend' as first argument.
document
.getElementById('button')
.addEventListener('click', () => {
document.getElementById('txtList')
.insertAdjacentHTML('beforeend', '<input type="text">');
});
JSBin link is here.

How to get value of another input field using javascript

How to find the value of text field using onblur() in next input field.
I tried:
function get_value() {
var inv_nrs;
inv_nrs = document.getElementsByTagName('text1').value;
alert(inv_nrs);
}
text1 is name of input which I am trying to get value.
text2 is name of input where onblur() is triggered.
Two problems:
To get elements by their name attribute, use document.getElementsByName(), not document.getElementsByTagName.
Since these functions return a collection, not a single element, you have to index them to get a specific element.
So the function should be:
function get_value() {
var inv_nrs;
inv_nrs = document.getElementsByName('text1')[0].value;
alert(inv_nrs);
}
Here's a simple snippet which illustrates a way to do this.
(You may wish to use alert in place of console.log)
document.getElementById("text2").onblur = function() {
console.log(document.getElementById("text1").value)
}
<input type="text" id="text1" value="123" />
<input type="text" id="text2" />
Are you looking for an element with id = "text1" or real name = "text1"?
At least if it's their id try getElementById("text1"), that returns one single element. If you talking about the name-attribute, take getElementByName("text1"), this may return more than one element (if there are more then one with the same name).
i think you want this???
function get_value()
{
var inv_nrs;
inv_nrs = document.getElementById('txt1').value;
document.getElementById('txt2').value=inv_nrs;
}
<input type="text" id="txt1" >
<input type="text" id="txt2" onblur="get_value()">
If you search with tagname then you need to insert a tagname:
document.getElementsByTagName('input')[whole_number].value which also
returns a live HTMLCollection
Eg. document.getElementsByTagName("input")[0].value; ,if this is the first textbox in your page.
You can get the value of an html element also on different ways:
document.getElementsByName('text1')[whole_number].value which also
returns a live NodeList
Eg. document.getElementsByName("searchTsxt")[0].value; if this is the
first textbox with name 'searchtext' in your page.
You can also get element by Id:
document.getElementById('IDHere').value to get the value of desired
box
You can also get it by way of Classname:
Use document.getElementsByClassName('class_name')[whole_number].value
which returns a Live HTMLCollection
Good luck

Input field limit 9 char and after 3 char automaticly ads "-"

<input id="myText" type="text" placeholder="XXX-XXX-XXX" /></input>
<script type="text/javascript">
document.getElementById("myText").value.substr(0, 9).match(/.{1,3}/g).join("-");
</script>
There are a few problems with your current JavaScript. First, your script will only run once when the page is loaded, meaning any input you enter into myText after that will never be processed. Consider binding to an event of myText - for example, the onkeyup event.
Another problem is that your JavaScript doesn't take into account existing dashes when splitting the value of myText into 3-character parts - this results in undesirable behaviour, where more and more dashes will be added to the value, at seemingly random positions.
Lastly, as mentioned by Tushar in the comments, you need to set the value of myText to the new, processed value you create. Otherwise this value ends up being unused and discarded, and your code appears to do nothing.
Putting this all together, the fixed code might look like:
var textInput = document.getElementById("myText");
textInput.onkeyup = function()
{
var dashlessInput = textInput.value.replace(/-/g, "");
textInput.value = dashlessInput.substr(0, 9).match(/.{1,3}/g).join("-");
};
<input id="myText" type="text" placeholder="XXX-XXX-XXX" /></input>
Hope this helps! Let me know if you have any questions.
For future reference - try to clearly state what your question by explaining what you want to achieve, and specifically indicating what problems you're facing. This way, you're more likely to attract good answers rather than downvotes.

How do I get user input from input area with Java Script and assign to a variable?

I'm trying to make a simple mad libs type game. To do so I need to do the following:
Have space that user can input text
Retrieve text that user inputted
Assign text to variables using Javascript
Place variables in Mad libs
I know how to do this using something like:
var userAnswer = prompt("Give me an answer");
However, I want to get the input from a text input field. I was trying to do the following but I got stuck:
Have input area with id="input1"
Create function that takes content of #input1 and assign to a variable.
Use button to run the function
I will then later use these variables in my story
<label for='input1'>Verb + ing</label><input id='input1'>
<script>
var setInputs = function() {
var space1 = document.getElementById("input1").innerHTML;
}
</script>
<button onclick="setInputs">Click me</button>
I'm I going about this the correct way?
Fiddle: http://jsfiddle.net/6rjf5k9n/
Try This
<label for='input1'>Verb + ing</label><input id='input1'>
<script>
var setInputs = function() {
var space1 = document.getElementById("input1").value;
alert(space1);
}
</script>
<button onclick="setInputs()">Click me</button>
.value gives you the currently-set value of a form element (input, select, textarea), whereas
.innerHTML builds an HTML string based on the DOM nodes the element contains.

Update placeholder text with new text onClick/onFocus

Here is one I just had come up and the solution baffled me and no search here at SO revealed anything.
Standard input field:
<input type="input" name="fName" placeholder="Your First Name">
But let us say I would like to update the placeholder text when somebody clicks on the field or when the field is onfocus via pressing the Tab key.
So it would become:
<input type="input" name="fName" placeholder="Your First Name Goes Here">
Just a very basic example of what it would do, by adding the "Goes Here" to the placeholder text.
Doable? Even possible to modify placeholder? Unknown to me.
If so and it is possible via pure JS or via jQuery, I would be entertained in seeing how.
This should do it (edit:added blur reset):
$('input[name=fName]').on("click focus",function(){
$(this).attr("placeholder","Your First Name Goes Here");
}).on("blur",function(){
$(this).attr("placeholder","Your First Name");
});
Updated Fiddle: http://jsfiddle.net/6tb8v/1/
To do it in pure JS, you should use addEventListener() to get the click/focus event and setAttribute() to set the placeholder attribute.
var elem = document.getElementsByName("fName")[0];
function appendPlaceholder () {
elem.setAttribute ("placeholder", "Your First Name Goes Here");
}
elem.addEventListener("click", appendPlaceholder);
elem.addEventListener("focus", appendPlaceholder);
elem.addEventListener("blur", function () {
elem.setAttribute ("placeholder", "Your First Name");
});
Here's a JS answer. I tend to dislike JQuery.
var myInpt = document.getElementsByTagName('input');
var key;
for(key in myInpt)
{
myInpt[key].addEventListener('click', updateInpt, true);
}
function updateInput(evt)
{
this.inpt = evt.srcElement;
var plchldrText = this.inpt.getAttribute('placeholder');
this.inpt.setAttribute('placeholder', plchldrText + ' Goes Here');
}
Of course, this attaches the click event to every input element on your page, as well as every time you click it, it adds the string ' Goes Here'. Haha. If you want to do it this way, maybe you should add an id to the input and collect it in JS that way. Just a thought and a simple example! Hope it helps!

Categories

Resources