How to get full string in .text() method in javascript? - javascript

I am working on javascript and html. I have table data. On the click of each td value I run a javascript function which get the text value of td and put as value in input tag generated dynamically. When I click the td text why I don't get the full string in my value?
I tried using inner Html and tried setting value.
<tr class="success">
<td id="name" ><a style="cursor: pointer;">Ravi Sharma</a></td>
</tr>
$('#name a').click(function() {
var name = $(this).text();
var html = '<input type="text" name="memberlist" value='+ name +'/> ';
});
Expecting:
<input type="text" name="memberlist" value="Ravi Sharma" >
Actual:
<input type="text" name="memberlist" value="Ravi" sharma>

Other answers will tell you why you got the result you did. It is tempting to try to solve the problem by just adding quotes, e.g.,
var html = '<input type="text" name="memberlist" value="'+ name +'"/> ';
This will work great if name is Ravi Sharma. But if you are constructing a chunk of HTML and trying to put the resulting string into an element's innerHTML you will have trouble if the variable name has double quotes in it!
name = 'Ravi O"Brien'
document.body.innerHTML = '<input type="text" name="memberlist" value="'+ name +'"/> '
This will expand into
value="Ravi O"Brien"
and your input box will contain only "Ravi O".
Sure you can use backticks and interpolation to solve this, or you can even try escaping the double quote characters with backslashes. Doing so is error prone. innerHTML is problematic anyway, and a big security concern. It is preferable to create the HTML elements yourself. You are using jQuery so the proper way to create your input element is:
$("<input/>", {
type: 'text',
value: name,
name: 'memberList',
})
There are ways to be safe with innerHTML but IMHO it should (always) be avoided.

HTML element attributes need to have quotes around their values. When you are doing your concatenating the single quotes get interpolated. So it assumes the first word is the only value.
Instead of:
var html = '<input type="text" name="memberlist" value='+ name +'/> ';
Try:
var html = '<input type="text" name="memberlist" value="'+ name +'"/> ';
#ray-toal brings up many good points about sanitization of your inputs and defending against XSS.

You are getting confused between the single and double quotes paring. I suggest using backticks as below:
var name = 'Ravi Sharma';
var html = `<input type="text" name="memberlist" value="${name}"/> `;
console.log(html);
When ever you need to insert a variable just encapsulate it within ${}. No more quotes pairing problems.

Just added an ID to the <a> tag (as it's the parent of the content text) and changed a bit of the JavaScript logic, hope it helps :
var text = document.getElementById("aName").innerHTML;
var output = '<p>The name below is the result of the event, not the original state !</p>';
document.getElementById("aName").addEventListener("click", function() {
document.body.innerHTML = output + text;
});
<tr class="success">
<td id="name" ><a id="aName" style="cursor: pointer;">Ravi Sharma</a></td>
</tr>
ALSO, reading again what you're needing, to achieve what you want, you pretty much just have to apply the same logic to the tag inside the var, then call the var name on the innerHTML event :
var text = document.getElementById("aName").innerHTML;
var input_txt = '<input type="text" name="memberlist" value="'+ text +'"/> ';
document.getElementById("aName").addEventListener("click", function() {
document.body.innerHTML = input_txt;
});
<tr class="success">
<td id="name" ><a id="aName" style="cursor: pointer;">Ravi Sharma</a></td>
</tr>

Reproduced your code and got answer.
1. Change string initialization from '' to `` to be able to interpolate variables.
2. In your expectations, you ask for '>', but code contains '/>' change that if needed.
3. Here your solution!
$('#name a').click(function() {
var name = $(this).text();
var html = `<input type="text" name="memberlist" value="${name}"/> `;
"use strcit";
$('#name a').click(function() {
var name = $(this).text();
var html = `<input type="text" name="memberlist" value="${name}"/> `;
console.log(html);
});
table, th, td {
border: 1px solid black;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie-edge">
<title>Stack Overflow</title>
<link rel="stylesheet" href="css/index.css">
<link rel="stylesheet" href="styles.css">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<table class="table">
<tr class="success">
<td id="name" ><a style="cursor: pointer;">Ravi Sharma</a></td>
</tr>
</table>
<script src="scripts/so.js"></script>
</body>
</html>
});

Browsers ignore the <tbody>, <tr>, and <td> tags and the corresponding end tags. This has not been specified in HTML specifications, since they do not define the parsing of syntactically erroneous documents. In the HTML5 draft, however, there is a description that defines the browser behavior in a manner that corresponds to the what browsers actually do: Tree construction.
This means that you cannot write an HTML document that contains, say, a element outside a table element. The HTML parser in a browser simply does not construct such document trees. (You can, however, construct such a document dynamically with client-side scription.)
$('#name').click(function() {
alert("asdfsdf");
var name = $(this).text();
var html = '<input type="text" name="memberlist" value='+ name +'/> ';
$("#test").text(html);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<tr class="success">
<td><a id="name" style="cursor: pointer;">Ravi Sharma</a></td>
</tr>
<div id="test"></div>

Related

How can I replace whole input field with its value in JavaScript or jQuery?

Say, I have an html input field.
<input type='text' class='txtData' />
In documentready method I set value of that input field.
$(".txtData").val(2);
Now I convert this html input field into string like below.
var sText = "<input type='text' class='txtData' />";
Now I want to replace this sText with $(.txtData).val().
How can I solve this? I google a lot but not find any solution
I find below solution which replace whole sText to " ".
sText.replace(/<input[^>]*>|<\/input>/gi, "");
But how can I replace it with selected input field's value?
Thanks in advance.
You can parse string to html using JQuery.parseHTML and then use the variable to update value.
example:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
var sText = "<input type='text' value='21' class='txtData' />";
var html = $.parseHTML(sText);
//alert('before update '+$(html).val())
console.log('before update '+$(html).val());
$(html).val(19);
//alert('after update '+$(html).val())
console.log('after update '+$(html).val());
});
});
</script>
</head>
<body>
<button>UPDATE TEST</button>
</body>
</html>

How to insert html from a button click

I am trying to insert a form when a button is clicked but cannot find a way that does not make me put all of the HTML on one line with back slashes or many ugly lines of code. Something that does not include adding on something line jQuery or php.
In essence: How can I make this...(that is all on one line)
<script>
function newMsg() {
document.getElementById("add_message").innerHTML = "<div class=\"message\">Add Message<br>Title: <input type=\"text\" id=\"title\"><br>Text: <input type=\"text\" id=\"message\"><br><br></div>";
}
</script>
Look a little more something like this (that has good formatting and on multiple lines)
<script>function newMsg() {function newMsg() {
document.getElementById("add_message").innerHTML =
"<div class="message">Add Message<br>
Title: <input type="text" id="title"><br>
Text: <input type="text" id="message"><br><br>
</div>";
}
</script>
Simply replace the first and last " of the right hand side with ' and remove all \
like this :
document.getElementById("add_message").innerHTML = '<div class="message">Add Message<br>Title: <input type="text" id="title"><br>Text: <input type="text" id="message"><br><br></div>';
.innerHTML = '<div class="message">Add Message<br>'
+ 'Title: <input type="text" id="title"><br/>'
+ 'Text: <input type="text" id="message"><br/><br/></div>';
You can do what hamism suggested as well as concatenate if one line is too long, this way you can make your code look slightly cleaner.
You may check this fiddle:
http://jsfiddle.net/7sqha4ks/
function myFunction(){
document.getElementById("add_message").innerHTML =
'<div class="message">Add Message<br>Title: <input type="text" id="title">
<br>Text: <input type="text" id="message"><br><br></div>';
};
If you're issue is just with formatting, you can use an array of lines and the join array method like this:
var html = [
'<div class="message">Add Message<br>',
'Title: <input type="text" id="title"><br>',
'Text: <input type="text" id="message"><br><br>',
'</div>'
].join("\n");
Alternatively, you could use a templating language such as Handlebars or Jade and precompile your templates.
Alternatively, you could use a multiline string hack like this:
https://github.com/sindresorhus/multiline
If you wanna get it on separate lines like that for easier readability create your html as a variable and concatenate with the "+" symbol. Also use single quotes for any quotes inside of the main html. Something like:
var html = "<div class='message'>Add Message<br>"
+ "Title: <input type='text' id='title'><br>"
+ "Text: <input type='text' id='message'><br><br>"
+ "</div>";
document.getElementById("add_message").innerHTML = html

jQuery remove too many fields

I am creating a form where the user can add fields one after the other. For each field I am setting a "remove" button. Each field is in a table, so I give a random id to the table, and pass this id to a removing function doing: $(random-id).remove().
The strange thing is that jQuery is removing all of the tables created by the user, as if the id is not taken into account
Why that can be?
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="http://code.jquery.com/ui/1.11.2/themes/smoothness/jquery-ui.css">
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script src="http://code.jquery.com/ui/1.11.2/jquery-ui.js"></script>
<script>
function delete_field(id)
{
$("#"+id+"").remove();
}
function add_form_field()
{
id = Math.random();
html = '<table id='+id+'>\
<tr><td>Label </td></tr>\
</table>\
\
<button onclick=delete_field('+id+')>remove</button>';
$("form").append(html);
}
</script>
</head>
<body>
<form>
</form>
<button onclick=add_form_field()> Add a field </button>
</body>
</html>
Don't use Math.random, rather increment a number and create ID like: #tab_NN.
Add an ID to your Form Element id=myForm
Delegate click events to dynamically generated delete buttons using .on()
While removing the table that matched the button data-* attribute, delete the button too using .add( this ) (where this stays for the clicked button)
var id = 0;
function delete_field(event){
event.preventDefault();
$("#tab_"+ $(this).data("remove")).add(this).remove();
}
function add_form_field(){
id += 1;
var html = '<table id="tab_'+ id +'">'+
'<tr><td>Label</td></tr>'+
'</table>'+
'<button data-remove="'+id+'" class="remove">remove</button>';
$("#myForm").append(html);
}
$('#addField').on('click', add_form_field);
$('#myForm').on('click', '.remove', delete_field);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="myForm"></form>
<button id="addField"> Add a field </button>
The code above allows you to have changes in the future markup cause it targets a specific ID, but in case your DELETE buttons will always be exactly after table than you can do it without assigning ID's, by simply using .prev("table"):
http://jsbin.com/wuqati/1/edit
function delete_field(event){
event.preventDefault();
$(this).prev("table").add(this).remove();
}
function add_form_field(){
var html = '<table>'+
'<tr><td>Label</td></tr>'+
'</table>'+
'<button class="remove">remove</button>';
$("#myForm").append(html);
}
$('#addField').on('click', add_form_field);
$('#myForm').on('click', '.remove', delete_field);
Math.random() produces a floating point number less than 1 which is invalid for an id. You can use a global variable to keep count of the rows created. Keep in mind that a CSS ID can not start with a digit. So append the number to a string before using it as an ID.
<script>
function delete_field(id)
{
$("#"+id+"").remove();
}
tableID = 1;
function add_form_field()
{
id = 'table-'+tableID;
html = '<table id='+id+'>\
<tr><td>Label </td></tr>\
</table>\
\
<button onclick=delete_field('+id+')>remove</button>';
$("form").append(html);
tableID++;
}
</script>
Why not simplify this by doing something like below.
$(".remover").click(function() {
$(this).parent().remove();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td>
<input type="text" placeholder="input One"/> <input type="button" class="remover" value="remove" />
</td> </tr>
<tr>
<td>
<input type="text" placeholder="input Two"/> <input type="button" class="remover" value="remove" />
</td> </tr>
<tr>
<td>
<input type="text" placeholder="input Three"/> <input type="button" class="remover" value="remove" />
</td> </tr>
</table>

How to send information from HTML <input> element to <span> using JavaScript .innerHTML?

I'm very new to JavaScript and trying to mimic an example in a book I'm reading. I would like to take what is input to a HTML element and send the data to a element using .innerHTML. I don't know what is wrong.
<!DOCTYPE html>
<html>
<head>
<title>JS Form</title>
</head>
<body>
<form id="date">
<table>
<tr><td><input type="text" name="user" placeholder="Please input name" onchange="greeting();"></td>
</tr>
<tr><td><span id="hello"></span></td>
</tr>
</table>
</form>
<script type="text/javascript">
function greeting() {
var user = document.date.user.value;
var hello = document.getElementById("hello");
hello.innerHTML = "How are you " + user;
}
</script>
</body>
</html>
Add name="date" to your form tag like below. Else document.date.user.value will not work.
<form id="date" name="date">
Another way to get around the issue, is accessing the date property of the window object.
window.date.user.value;
This is possible because you've set an id on the form.
Or you might consider accessing the form using its id and then get user value as follows:
var user = document.getElementById("date").user.value;
For simplification, and depending on your browser, you could use document.querySelector. Take a look at this very helpful SO post:
JavaScript: how to get value of text input field?
you should do this first:
var user= document.getElementsByName("user");
var hello = document.getElementById("hello");
hello.innerHTML = "How are you " + user[0].value;

place value into input box from query string not working

how can I take the value of a query string and place it into an input box? Currently I have:
<input type="text" name="spouse" id="spouse" value="<script type="text/javascript">
document.write("Name: " + Request.QueryString("spouse"));
</script>"/>
But that only takes the script take and all of its contents and places it into the input box.
I would like to be able to take my query string that is coming from this code:
<tr >
<td><input type="text" name="n1" value="Duck, Donald" /></td>
<td><input type="text" name="n2" value="Daisy" /></td>
<td><input type="button" value="Show" title="Show"
onclick="location.href='example123.html?name=' + escape(this.form.n1.value)+ '&spouse=' + escape(this.form.n2.value);" />
</td>
and have the value for name or spouse appear inside of an input box. What is the proper way to place a value into an input box from a query string?
Request.QueryString is not a native JavaScript function. Use the document.location object and parse out the value you want.
Perhaps use the onload function to perform the action you need. This calls your function once the document has been fully loaded and so you know all tags in the html will exist at this point and be can be referenced properly.
eg.
<html>
<head>
<title>Value Setting</title>
<script type="text/javascript">
window.onload = (function() {
document.getElementById('spouse').value = "one way";
document.forms[0].elements[1].value = "another way";
/* note elements refers to only input children */
});
</script>
</head>
<body>
<form id="myform">
<div>
<input id="first-field" value="first-field" onchange="this.value += ' an example';"/>
</div>
<div>
<p>
<input id="spouse" value="spouse"/>
</p>
</div>
</form>
</body>
</html>
You can't embed elements in attributes as that isn't valid html. Though some attributes can get evaluated as javascript. Namely attributes such as action, onchange, onclick and so on.

Categories