I have a dynamic web page where the content may contain between 1 and 10 links, provided in text boxes, similar to the following:
<input size="50" id="link" value="http://Something.Something" type="text">
<input size="50" id="link" value="http://SomethingElse.Something" type="text">
I need javascript to be able to read all of the links, and be able to manipulate the data (store in array, output to screen, etc)
I know that I can read a single id using the following
var link = document.getElementById('link');
Which will return the first match - but, how can I do a loop or obtain all the values for all the links, bearing in mind that the number of links cannot be determined beforehand?
P.S. I have tried using getElementsByTagName('input') but there are more inputs on the page, which means it's getting more results than I'd like it to get.
You can make them all have names and search by name.
<input name="vrow" value="0" type="text"/>
<input name="vrow" value="0" type="text"/>
<input name="vrow" value="0" type="text"/>
<input name="vrow" value="0" type="text"/>
Then you can get it with:
var vrows = document.getElementsByName("vrow");
alert(vrows.length);
Give them all a common class and access using document.getElementsByClassName('class').
IDs should be unique for each element. You could use document.getElementsByClassName or document.querySelectorAll(".class"); and then use the class name (assuming relatively modern browser). Or use document.getElementsByTagName() and then iterate through the elements comparing with the class.
Attach a jQuery lib and you will be able to do something like:
$('input[type=text]').each(function(i, val){
alert($(this).val());
});
Related
This seems like it should be simple but I can't get it to work. The environment I am working in requires that I use NAME instead of ID, so I am making certain that all of my names are unique. I simply want to get two numbers from input fields, add them together and put the answer into a read only field.
<input type="number" name="first_num"></input>
<input type="number" name="second_num"></input>
<input type="number" name="sum_of_num" readonly></input>
<button name="perform_sum" onclick="document.getelementsbyname("sum_of_num")[0].value=(document.getelementsbyname("first_num")[0].value+document.getelementsbyname("second_num")[0].value)">Sum</button>
<input type="number" name="first_num"></input>
<input type="number" name="second_num"></input>
<input type="number" name="sum_of_num" readonly></input>
<button name="perform_sum" onclick="document.getElementsByName('sum_of_num')[0].value = (parseInt(document.getElementsByName('first_num')[0].value) + parseInt(document.getElementsByName('second_num')[0].value))">Sum</button>
getelementsbyname -> getElementsByName (javascript is case sensitive)
" -> ' (if you use double apex in html you have to slash your double apex in javascript or have to use single apex in javascript, or reverse)
.value is string, you need to convert it in int
You'll need to use single quotes, otherwise it thinks the attribute is closed. Also the functions are case-sensitive so it should be getElementsByName
from
<button name="perform_sum" onclick="document.getelementsbyname("sum_of_num")[0].value=(document.getelementsbyname("first_num")[0].value+document.getelementsbyname("second_num")[0].value)">Sum</button>
to
<button name="perform_sum" onclick="document.getElementsByName('sum_of_num')[0].value=(document.getElementsByName('first_num')[0].value+document.getElementsByName('second_num')[0].value)">Sum</button>
jQuery answer because it's the easiest (even though you didn't tag jQuery):
$("button").click(function () {
var first_num = Number($("input[name='first_num']").val());
var second_num = Number($("input[name='second_num']").val());
$("input[name='sum_of_num']").val(first_num + second_num);
});
jQuery makes it super simple to select by attributes such as name.
you have to use parseInt function else it will just concat two box values.
I have a dynamically created page with repeated elements, like so:
<input type="file" name="file1">
<input type="file" name="file2">
<input type="file" name="file3">
I would like to add some data to each of these elements for use in JavaScript. Originally I used "spare" attributes that while valid on an input tag were not valid on a file type input tag, eg, size. I have now added it to the class attribute, but have to use a regex to get it out again. Neither of these methods seem very satisfactory, is there a better way?
Quite often I see data added through attributes that are prefixed with data-, for instance:
<input type="file" name="file1" data-filesize="871">
jQuery even has function to conveniently read that information, for instance like this:
var filesize = $('input[name="file1"]').data('filesize');
And, to write the data, attr can be used:
$('input[name="file1"]').attr("data-filesize", filesize );
See also: HTML 5 data atributes
You can use attributes with a name starting with "data-"
Use the data attribute: <input data-something="somevalue" />
with attribute start with data- you can use your own other name appending to it.
Go through this examples
This question already has answers here:
JavaScript getElementByName doesn't work
(4 answers)
Closed 9 years ago.
I need to make "readonly" a text field by place javascript code inside external JS file. I can't modify html directly because the page is located on remote server..but I can interact by adding code in external JS who is located on my own host.
The html is this:
<form id="newunitform" class="left" action="page.php" style="width:600px" method="post">
<fieldset>
<ul>
<li>
<label for="add">
<input type="text" value="" name="add">
<input type="hidden" value="" name="remove">
<input type="hidden" value="105" name="resource_id">
<input type="hidden" value="" name="editid">
</li>
</ul>
<label for="submit"> </label>
<input class="button" type="submit" value="Add name" name="submit">
</fieldset>
</form>
I tried several combination such this:
document.getElementByName('add').readOnly=true;
or this:
var add = document.getElementByName('add');
add.readOnly = true;
or this:
document.getElementById('newunitform');
document.getElementByName('add').readOnly=true;
but none work.
As Rocket Hazmat suggests in the comment to your question, you should use
document.getElementsByName('add')[0].readOnly=true;
document.getElementsByName('name')
returns an array. You need to use brackets or .item() to point to your element.
I suggest you using this one, in my opinion it is a better solution:
var newUnitForm = document.getElementById('newunitform');
newUnitForm.add.readOnly = true; //or newUnitForm['add'], it's the same
That's true -- it's either getElementById (single element) or getElementsByName which access all the elements in the DOM that have the name you're looking for.
Once you change Element to Elements you should be able to set the readOnly attribute.
You could also try, document.getElementByNames('someElement').disabled = true; but be careful if there are multiple elements with the same name.
Also -- because syntax like this has tripped me up any number of times, if a function doesn't work as expected, I'll make sure I'm getting the object I think I'm getting by alerting some aspect of the element.
e.g. alert(document.getElementsByName('someElement').length) or alert(document.getElementsByName('someElement').name)
Good luck
If you know there is only one element named "add", you can try something like this:
var elem = document.getElementsByName("add")[0];
elem.setAttribute("readonly", "true"); // or elem.readOnly = true;
If you know there is only one element named "add" inside the "newunitform" form, use LightStyle's suggestion:
var elem = document.getElementById("newunitform").add;
elem.setAttribute("readonly", "true"); // or elem.readOnly = true;
In any case, make sure the snippet is executed after the element in question has been rendered (e.g. you could place it in body's onload method.
What is a common way to pass data for formula fields, to specify a quantifier. I would currently do as follows:
<input type="text" name="myfield" class="inputfieldstyle quantified" id="q_12" value="foo" />
where q_12 is generic.
But there some inherent problems with the approach:
What if i want to give it an id for some js/css reason?
q_12 is not easy to read with js:
var quant =
parseInt(element.id.split('_').pop())
id is not made for passing values
How should I handle this? Is there a common way? Is there a way suggested by w3c?
A good and simple way is to use hidden fields :
<input type="hidden" name="myname" value="my_value" id="my_id">
You could extend the hidden fields idea of Guillaume Lebourgeois. If you're worried about having two inputs for each, you could always adopt the "data-" attribute approach as detailed in the following link: http://ejohn.org/blog/html-5-data-attributes/
<input type="hidden" name="myname" id="my_id"
data-myData1="somedata" data-myData2="somemoredata" value="" >
and then use getAttribute to return the value (http://www.devguru.com/technologies/javascript/17457.asp):
document.getElementbyId("my_id").getAttribute("data-myData1")
document.getElementbyId("my_id").getAttribute("data-myData2")
Or if you are using jQuery:
$("#my_id").attr("data-myData1")
Of course, you would have to roll this up into the value before passing across pages, but its still a possiblity.
I have a form that I want to be used to add entries. Once an entry is added, the original form should be reset to prepare it for the next entry, and the saved form should be duplicated prior to resetting and appended onto a div for 'storedEntries.' This much is working (for the most part), but Im having trouble accessing the newly created form... I need to change the value attribute of the submit button from 'add' to 'edit' so properly communicate what clicking that button should do. heres my form:
<div class="newTruck">
<form id="addNewTruck" class='updateschedule' action="javascript:sub(sTime.value, eTime.value, lat.value, lng.value, street.value);">
<b style="color:green;">Opening at: </b>
<input id="sTime" name="sTime" title="Opening time" value="Click to set opening time" class="datetimepicker"/>
<b style="color:red;">Closing at: </b>
<input id="eTime" name= "eTime" title="Closing time" value="Click to set closing time" class="datetimepicker"/>
<label for='street'>Address</label>
<input type='text' name='street' id='street' class='text' autocomplete='off'/>
<input id='submit' class='submit' style="cursor: pointer; cursor: hand;" type="submit" value='Add new stop'/>
<div id='suggests' class='auto_complete' style='display:none'></div>
<input type='hidden' name='lat' id='lat'/>
<input type='hidden' name='lng' id='lng'/>
</form>
</div>
ive tried using a hundred different selectors with jquery to no avail... heres my script as it stands:
function cloneAndClear(){
var id = name+now;
$j("#addNewTruck").clone(true).attr("id",id).appendTo(".scheduledTrucks");
$j('#'+id).filter('#submit').attr('value', 'Edit');
$j("#addNewTruck")[0].reset();
createPickers();
}
the element is properly cloned and inserted into the div, but i cant find a way to access this element... the third line in the script never works.
Another problem i am having is that the 'values' in the cloned form revert back to the value in the source of the html rather than what the user inputs.
advice on how to solve either of these issues is greatly appreciated!
I think you want to use find not filter
$j('#'+id).find('#submit')
That should work in practice, though you've got problems there because there are multiple elements with the same id. I'd change your HTML to use classes, or in this specific case, you don't need either:
$j('#' + id).find(":submit")
have you tried using .val()? and instead of .filter(), use .find()
$j('#'+id).find(':submit').val('Edit');
nickf solution works. (just wrote a piece of code to check that). Do check the definition of filter in jquery documentation.
Reduce the set of matched elements to those that match the selector or pass the function's test.
You have use find in this case. Also as nick mentioned having multiple elements with same id is troublesome, especially when you are doing dom manipulation. Better go with appropriate classes.