I have a table that localstorage value is saved and displayed in the th.
I want to write a function that will delete the text of the localstorage and open input field on click. I tried something like this:
<html>
<body>
<table style="float: right ; padding-left: 10px;" id="table">
<tr>
<th id="hello" style="padding-left:24px; text-align: center;" class="button" id="0"><input id="inside" name="inside" type="text" ></th>
</table>
<button onclick="again();">again</button>
<script>
function again() {
document.getElementById("hello").innerHTML=input;}
</script>
</body>
</html>
but it doesn't work. Can somebode explain what is the mistake? thank you very much!
Your function again() is setting the innerHTML of the th to the value of a variable called input (that does not exist).
You have to extract the value of the input field and write that (string) as the innerHTML of the head. Try this:
function again(){
const tableHeaderElement = document.getElementById("hello");
const userEnteredData = tableHeaderElement.getElementsByTagName('input')[0].value;
tableHeaderElement.innerHTML = userEnteredData;
}
the second statement is retrieving an HTMLCollection of input tags inside the header. Your HTMLcollection will only have one member but must be referenced by index, like an array, hence [0]. Obviously .value extracts the value property of that element, which is the text entered by your user.
Depending on use, there may be security concerns about adding user-entered data into an html element as, if they entered script tags and valid javascript, they might be able to do things you don't want them to. It is usual to either screen user-entered data, 'sanitise it', to remove active code, or, easier but soon to be deprecated, escape data before writing it to an html element.
Related
Its as simple as it gets, i want to change the text within <td> to be whatever the user enters in the prompt, i have tried many solutions. Such as putting the script element below body. Here is the java script code however it doesnt work although i assume everything is as it should.
var yourname = prompt("Enter your name");
document.getElementById("name").innerHTML = yourname;
Here is the HTML
<html><head>Cant figure this out</head>
<body>
<table>
<tr>
<td>Name</td>
</tr>
<tr>
<td id = "Name"></td>
</tr>
</table>
</body>
</html>```
I see a couple of problems with the code:
The html doesn't have a script-tag to use the javascript. Without that it won't load. To avoid these kind of problems please make the smallest code that have the problem and use copy-paste to get the exact code in questions.
Name != name. The case of the id differs between the html and the javascript.
You have additional characters last in the html: ```
I'm not a frontend developer and don't know if this will solve your current problem. But those issues should be handled either way.
in your HTML you gave the an id of "Name", yet in the javascript script you are searching for an element with id "name". The id is case sensitive, so you would have to search for "Name", not "name".
I am getting data from the server and iterating over it to create a table and then I am using a form to store an id to local storage using javascript. Here is code snippet
<table>
<tr><th>Product ID</th></tr>
{{range .}}
<td ><form onsubmit="save_data()" action="/" method="get"><button class="btn btn-info pid" id="pid" name="{{.puid}}" value="{{.puid}}">Update</button></form></td>
{{end}}
<table>
<script>
function save_data() {
var input = document.getElementByID("pid");
localStorage.setItem("id", input.value);
}
</script>
However every time, no matter of which table row's "update" button I click, everytime only the ID of the first table row element is getting stored.
Is there a way I can generate unique IDs and reference it in Javascript when ranging over the data.
Thanks
In the loop You have
<button class="..." id="pid" name="{{.puid}}" value="{{.puid}}">Update</button>
which means that all buttons have id attribute whith the same value pid. This is an bug as id-s must be unique in the document. And when you call
document.getElementById("pid");
the first element matching the id="pid" is returned. That explains why "only the ID of the first table row element is getting stored".
To create unique id for each row you could use something like
{{range $index, $value := .}}
...<button class="..." id="pid{{$index}}" name="{{$value.puid}}" value="{{$value.puid}}">Update</button>...
{{end}}
but then you have a problem how to know which form was submitted when your save_data() event fires. To solve this you could send the current form or row id as a parameter, something like
{{range $index, $value := .}}
<td><form onsubmit="save_data(this, {{$index}})" action="/" method="get">...</form></td>
{{end}}
function save_data(form, rowno) {
var input = document.getElementById("pid"+rowno);
localStorage.setItem("id", input.value);
}
I'm just trying to do this from the chrome console on Wikipedia. I'm placing my cursor in the search bar and then trying to do document.activeElement.innerHTML += "some text" but it doesn't work. I googled around and looked at the other properties and attributes and couldn't figure out what I was doing wrong.
The activeElement selector works fine, it is selecting the correct element.
Edit: I just found that it's the value property. So I'd like to change what I'm asking. Why doesn't changing innerHTML work on input elements? Why do they have that property if I can't do anything with it?
Setting the value is normally used for input/form elements. innerHTML is normally used for div, span, td and similar elements.
value applies only to objects that have the value attribute (normally, form controls).
innerHtml applies to every object that can contain HTML (divs, spans, but many other and also form controls).
They are not equivalent or replaceable. Depends on what you are trying to achieve
First understand where to use what.
<input type="text" value="23" id="age">
Here now
var ageElem=document.getElementById('age');
So on this ageElem you can have that many things what that element contains.So you can use its value,type etc attributes. But cannot use innerHTML because we don't write anything between input tag
<button id='ageButton'>Display Age</button>
So here Display Age is the innerHTML content as it is written inside HTML tag button.
Using innerHTML on an input tag would just result in:
<input name="button" value="Click" ... > InnerHTML Goes Here </input>
But because an input tag doesn't need a closing tag it'll get reset to:
<input name="button" value="Click" ... />
So it's likely your browsers is applying the changes and immediatly resetting it.
do you mean something like this:
$('.activeElement').val('Some text');
<input id="input" type="number">
document.getElementById("input").addEventListener("change", GetData);
function GetData () {
var data = document.getElementById("input").value;
console.log(data);
function ModifyData () {
document.getElementById("input").value = data + "69";
};
ModifyData();
};
My comments: Here input field works as an input and as a display by changing .value
Each HTML element has an innerHTML property that defines both the HTML
code and the text that occurs between that element's opening and
closing tag. By changing an element's innerHTML after some user
interaction, you can make much more interactive pages.
JScript
<script type="text/javascript">
function changeText(){
document.getElementById('boldStuff').innerHTML = 'Fred Flinstone';
}
</script>
HTML
<p>Welcome to Stack OverFlow <b id='boldStuff'>dude</b> </p>
<input type='button' onclick='changeText()' value='Change Text'/>
In the above example b tag is the innerhtml and dude is its value so to change those values we have written a function in JScript
innerHTML is a DOM property to insert content to a specified id of an element. It is used in Javascript to manipulate DOM.
For instance:
document.getElementById("example").innerHTML = "my string";
This example uses the method to "find" an HTML element (with id="example") and changes the element content (innerHTML) to "my string":
HTML
Change
Javascript
function change(){
document.getElementById(“example”).innerHTML = “Hello, World!”
}
After you clicked the button, Hello, World! will appear because the innerHTML insert the value (in this case, Hello, World!) into between the opening tag and closing tag with an id “example”.
So, if you inspect the element after clicking the button, you will see the following code :
<div id=”example”>Hello, World!</div>
That’s all
innerHTML is a DOM property to insert content to a specified id of an element. It is used in Javascript to manipulate DOM.
Example.
HTML
Change
Javascript
function FunctionName(){
document.getElementById(“example”).innerHTML = “Hello, Kennedy!”
}
On button Click, Hello, Kennedy! will appear because the innerHTML insert the value (in this case, Hello, Kennedy!) into between the opening tag and closing tag with an id “example”.
So, on inspecting the element after clicking the button, you will notice the following code :
<div id=”example”>Hello, Kennedy!</div>
Use
document.querySelector('input').defaultValue = "sometext"
Using innerHTML does not work on input elements and also textContent
var lat = document.getElementById("lat").value;
lat.value = position.coords.latitude;
<input type="text" id="long" class="form-control" placeholder="Longitude">
<button onclick="getLocation()" class="btn btn-default">Get Data</button>
Instaed of using InnerHTML use Value for input types
I'm a beginner in js and jquery library. I'd like to get an array of input fields with a particular name, and validate input. Each of my input fields have a name like NS[0], NS[1] etc. The total number of fields will have to be determined by the code, since the fields are generated by javascript.
I know that I can have jquery address the individual object like this:
$("input[name=NS\\[0\\]]").val() for <input type="text" name="NS[0]">.
However, how can I get an array of all these similiar elements, from NS[0] to NS[x] where x has to be determined based on how many fields have been generated? I already have other fields with different name patterns sharing the same css class, so using class is not an option. These boxes are in a particular div area, but in the same area are other input fields, so choosing all input boxes of the same area selects them as well.
In other words, how do I use jquery to check the name of each input field, after getting the entire array of input fields, to check each individual name?
Since I have input fields of various names in the area determined by the table id CNTR1, I would select them with $('#CNTR1 input'). I can also select individual fields by using $("input[name=]"). However, what I want to do, is to select everything under $('#CNTR1 input'), and then run a loop on their names, checking whether the names match a predetermined criteria. How can I do that?
The html code:
<table class="table" id="cnservers">
<thead>
<tr>
<th>Type</th>
<th>Preference</th>
<th>Value</th>
<th>Name</th>
</tr>
</thead>
<tr id="CNTR0">
<td>CNAME</td><td><input type="text" name="CN_PREF[0]" value=""></td><td>
<input type="text" name="CN_VAL[0]" value=""></td><td>
<input type="text" name="CN_NAME[0]" value="">
<a class="btn btn-danger" onclick="DelField(this.id);" id="CN_D0" >
<span class="btn-label">Delete
</span>
</a>
<a class="btn btn-primary" onclick="addField('cnservers','CN',10);" id="CN_A0" >
<span class="btn-label">Add
</span>
</td></tr>
</table>
[1]: http://i.stack.imgur.com/bm0Jq.jpg
I must be missing something. Is there a reason you can't use the http://api.jquery.com/attribute-starts-with-selector/?
$('#CNTR1').find('input[name^="NS"]')
Regarding,
However, what I want to do, is to select everything under $('#CNTR1 input'), and then run a loop on their names, checking whether the names match a predetermined criteria. How can I do that?
$("#CNTR1 input").each(function(index, elem) {
var $elem = $(elem),
name = $elem.attr('name');
var nameMatchesCondition = true; // replace with your condition
if (nameMatchesCondition) {
// do something!
}
});
EDIT 1:
Well, id is still an attribute of an html element. So you could do $('[id^="CNTR1"]') ... The value of the id attribute of an element doesn't contain the #. It's only part of the css/jquery selector. When using attribute style selectors, you don't need it. Though I can't comment on the performance of this.
Ideally, you want to attach a second class, say js-cntr to all elements that you created with an id starting with CNTR. Even though different name pattern elements may already have one class, that class is for styling. There is no stopping you from attaching custom classes purely for selection via js. This is an accepted thing to do and which is why the class name starts with js-, to denote that its purely for use via js for selection.
Try this
HTML
<table id="CNTR1">
<tr>
<td>CNAME</td>
<td><input type="text" name="CN_PREF[1]" id="CN_IN[1]"></td>
<td><input type="text" name="CN_VAL[1]"></td>
<td><input type="text" name="CN_NAME[1]"></td>
</tr>
</table>
JS
$(document).ready(function(){
$("#CNTR1 input").each(function() {
console.log($(this).attr("name"));
// Match With predetermined criteria
});
});
Use jQuery's .filter method, with a filter function:
filterCritera = /^CN_NAME\[/; // or whatever your criteria is
var inputs = $('#CNTR0 input');
// you could also cache this filter in a variable
inputs.filter(function(index){
return filterCritera.test(this.name);
}).css('background','red');
jsbin
The markup you posted does not the markup described in your question ( it does not contain NS[0]) but you can substitute it in the reguluar expression above.
I'm trying to get a variable in JS code to be displayed within a DIV within a table. I've cut the code down for simplicity just trying to get this working properly.
Firebug is reporting:
document.getElementById("valuelabel") is null
Here is the code:
<table>
<tbody>
<tr>
<td>
Value:
</td>
<td>
<div id="valuelabel"></div>
</td>
</tr>
</tbody>
</table>
<script language="javascript" type="text/javascript">
var mktValue = "12000";
document.getElementById("valuelabel").value = mktValue;
</script>
The mktValue will be a dynamically assigned numeric value; a textbox entry from another form. I just put "12000" in for testing purposes.
Within Firebug, it's shows the following for the dynamically assigned value.
var mktValue = '120700';
Thanks..
Divs don't have a "value", they do however have "innerHTML"
document.getElementById("valuelabel").innerHTML = mktValue;
div elements don't have a value (only form fields do). You can set the div's content via textContent (just text) or via innerHTML (HTML):
document.getElementById("target1").textContent = "This is normal text, <and> aren't special here.";
document.getElementById("target2").innerHTML = "This is HTML text, so <strong>tags</strong> are rendered as elements.";
<div id="target1"></div>
<div id="target2"></div>
you can use jquery to insert value into the specific id by using
$("#valuelabel").html(mktValue)