Populate an input field with a string that contains a double quote
I'm getting a value back from the server that contains a double quote in it. I need to populate an input tag with the value.
I've tried using escape(myVariable), but that converts the spaces to %20, etc. I suppose I could write an if/then that says if there's a double quote in the field, then use value='', but then what do I do if they have both double and开发者_运维百科 single quotes in the field?
input.value = val.replace(/"/g, '"');
Replace double quotes with "
.
I'm getting a value back from the server that contains a double quote in it.
You flagged your question as "javascript" so I assume you are loading this server value via ajax.
If the variable containing your value has already been assigned there is no reason to encode anything.
Here is a sample script that takes a variable that has already been assigned and puts it into a new form element. As you can see, the form element has no problem at all displaying both single and double quotes at the same time.
<html>
<body>
<form id='myform'></form>
<script type='text/javascript'>
var myField = "James' answer is \"the best\"";
var i = document.createElement('input');
i.type = 'text';
i.name = 'testField';
i.value = myField;
document.getElementById('myform').appendChild(i);
</script>
</body>
</html>
$("#input").val(unescape('"test " value" "'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
Test value: <input type="text" id="input" />
The Best Solution is Use htmlentities in php language:
<input value="<?php echo htmlentities($value);?>">
Worked in all cases:
1) Single Quote
example: Julia's cat
2) Double Quote
example: John"s Bike
Enjoy and Share the code to save other's life :)
精彩评论