Access and add fields with a button in HTML - javascript

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.

Related

How do I loop through each substring in a string and do stuff at that substring's location?

I want to loop through each substring in a string and do stuff at that substring's location, but after a lot of googling I can't figure out how to do it.
Basically, I have a variable containing a string with HTML code that will be appended to a div. The string contains HTML code for a number of input fields. I want to find each occurence of the substring name=", then search for the next occurence of a quotation mark (i e the end of the variable name, which can be different every time), and insert two square brackets [] before the quotation mark. The point of this is to convert the HTML input variable to an array in this case.
I'm imagining something like this (pseudo code warning):
function changeNameVariableIntoArrayVariable(htmlString) {
var subString = "name=\"";
var insertString = "[]";
foreach (subString in htmlString) {
find the next quotation mark (\") closest to the right of subString;
htmlString.insert(insertString to the left of quotationmark);
}
return htmlString;
}
Can this be done/is this a good idea? Thanks.
EDIT: From a request in the comments, here's an example of what might be the input htmlString and what the expected output should be:
Input:
<div class="select-new-container">
<label>Name:<br>
<input style="width:300px;" type="text" name="artist">
</label><br>
<label>Lifespan:<br>
<input style="width:300px;" type="text" name="artistlife">
</label><br>
<label>Instrument:<br>
<input style="width:300px;" type="text" name="artistrole">
</label><br>
</div>
Expected output:
<div class="select-new-container">
<label>Name:<br>
<input style="width:300px;" type="text" name="artist[]">
</label><br>
<label>Lifespan:<br>
<input style="width:300px;" type="text" name="artistlife[]">
</label><br>
<label>Instrument:<br>
<input style="width:300px;" type="text" name="artistrole[]">
</label><br>
</div>
It's a bad idea to parse HTML with regular expressions. But a simple search & replace shouldn't hurt too much.
htmlString.replace(/(name="[^"]+)(")/g, '$1[]$2');
But in general, this looks like a "do my homework for me" question, so it might be more helpful to actually learn about the basic elements of JavaScript like regular expressions.
I know this is not exactly what you've asked for, but if it was real non-string HTML then you could simply access the name attribute through getAttribute DOM object method.
HTML:
<input name="hello" />
JS:
// access the value in name attribute
var nameAttrVal = document.getElementsByTagName("input")[0].getAttribute("name");
// manipulate it
nameAttrVal = nameAttrVal + "[]";
console.log(nameAttrVal); // prints "hello[]"

Get the value of element using javascript by its class name

hi everyone I have an element like this :
<div class="price-box">
<span class="regular-price" id="product-price-27">
<span class="price">
...
</span>
</span>
</div>
<input type="text" name="qty" id="qty" maxlength="12" value="1" title="Qty" class="input-text qty" />
i have tried to get the value using this line
document.getElementByClassName('input-text qty').value="myvalue"
but that didn't work
how can I get the value without jquery?
note : I've included prototype.js in my project !
what about this one too :
<button type="button" title="Add to Cart" class="button btn-cart" onclick="productAddToCartForm.submit(this)"><span><span>Add to Cart</span></span></button>
I want to disable it using Javascript and by its class name !!!?
You might be looking for querySelector:
document.querySelector( ".input-text.qty" );
This returns a single item, rather than a NodeList. If you would like a NodeList instead, use the alternative querySelectorAll. Keep in mind that these methods take CSS Selectors. The selectors you can use are limited to the browser this code is executed in. Keep it simple.
These two methods have better browser support than getElementsByClassName, so I would encourage you to use them instead of taking your current approach.
Demo:
Since you are using Prototype in the page already, you may find this element using the "double-dollar" method:
$$('.input-text.qty');
As others have pointed out above, this returns an array of matched elements (or an empty array, if you don't have anything on the page that matches). So the easiest way to do anything to the result is with invoke():
$$('.input-text.qty').invoke('setValue', 'myvalue');
or
$$('.input-text.qty').invoke('disable');
Any of the Prototype Element methods can be invoked in this manner. If you want to do something custom to the element(s) based on some attribute, you can use each() instead:
$$('.input-text.qty').each(function(elm){
if (elm.frobber == 'froom') elm.remove();
});
Firstly, its getElementsByClassName (elements is plural) -- this will return an array of elements that satisfy the condition. You must specify the index of the array to modify the element properties:
document.getElementsByClassName('input-text qty')[0].value="myvalue"
You have id="qty" so forget class, just use
document.getElementById('qty').value = "myvalue";
Which is most efficient.
Other dom native methods like getElementsByClassName/TagName(note there are s after Element) returns an array like object NodeList.
You need to use index or loop to access it.
You error is that you using:
1) getElementByClassName instead of getElementsByClassName
2) getElementsByClassName returns array so you must get [0] element
So try this one:
var p = document.getElementsByClassName('input-text qty')
console.log(p[0])
p[0].value = "MyValue"
Demo
getElementByClassName() returns the array of matched elements, so to acces the first element of array use 0 index like
document.getElementsByClassName('input-text qty')[0].value="myvalue";
Or
You can use the id(qty) from input tag, and put the value on this tag by getElementById() something like
<input type="text" name="qty" id="qty" maxlength="12" value="1" title="Qty" class="input-text qty" />
document.getElementById('qty').value="myvalue";

Javascript get values of multiple text fields

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());
});

Text field should not accept Zero or Negative values? Only positive values are allowed

Text field should not accept Zero or Negative values.
As it is an amount field it should accept only positive values are allowed.
my sample code is here:
<td><spring:message code="amount"/><spring:message code="label.mandatory"/></td>
<td><form:input path="amount" /></td>
Changing the value of a control programatically doesn't dispatch a change event, so either put that logic as part of whatever is changing the value, or dispatch a change event yourself.
It may be better to set the default value of the name input (which seems an inappropriate name if it has a number value and especially if the form has a name) to zero and make it readonly. Also, move the code into a function. But here's a solution based on your original:
<input type="text" name="name" value="0" readonly>
<input type="button" value="up" onclick="
this.form.name.value = ++this.form.name.value;
">
<input type="button" value="down" onclick="
var el = this.form.name;
var value = el.value;
el.value = value < 1? 0 : --value;
">
Note that the values of form controls are strings, so be careful with using the + operator. It will do concatenation instead of addition if you aren't careful.

Make readonly using getElementByName? [duplicate]

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.

Categories