Javascript Code inside input value - javascript

I use Maxminds GEOIP tool and just call this after the body:
<script type="text/javascript" src="http://j.maxmind.com/app/geoip.js"></script>
To print out the City and State I just paste this into the HTML doc:
<script>document.write(geoip_city());</script>
<script>document.write(geoip_region());</script>
I want to pass those values in hidden inputs that I can submit and assign to variables. What I want is this, but obviously the syntax is way off:
<input type="hidden" name="city" value="<script>document.write(geoip_city());</script>" />
I've tried searching for it here but couldn't find an answer, can anybody help? Thanks!

I would write this (using jQuery) as:
var geo_city = geoip_city();
var geo_region = geoip_region();
$(document).ready(function(){
$("#city").val(geo_city);
});
<input type="hidden" id="city" name="city" value="" />
This code will take the variable geo_city and put it in your hidden text field that has the ID city.

I'd suggest adding a class to the elements you want populated by the geoip service, such as the obvious geoip class-name, and using a map of the geoip functions to populate the values of the hidden input elements based on their name, such as (untested, and, without a public API, untestable unfortunately):
var geoipMap {
'city' : geoip_city(),
'region' : geoip_region(),
'country' : geoip_country() // and so on...
};
var inputs = document.getElementsByTagName('input'),
geoipInputs = [];
for (var i = 0, len = inputs.length; i < len; i++) {
if (inputs[i].className.indexOf('geoip') !== -1) {
geoipInputs.push(inputs[i]);
}
}
for (var i = 0, len = geoipInputs; i < len; i++) {
geoipInputs[i].value = geoipMap[geoipInputs[i].name];
}

Related

JavaScript changing value of custom attribute by searching another custom attribute

thanks for reading.
So the input tags don't have an ID or a class name.
The value attribute is also custom.
This is what I was trying.
HTML
<input name="password" data-value="">
.
#"var aTags = document.getElementsByTagName('input');
var searchText = 'password';var found;
for (var i = 0; i < aTags.length; i++)
{
if (aTags[i].textContent == searchText){found =
aTags[i].setAttribute('data-value','123456789');
alert(found.getAttribute('data-value')); break;}
}");
or
var myInput=$('input[data-value='']').setAttribute('data-value','12345678');
alert(myInput.getAttribute('data-value'));
I tried using get elements by name, but there is nothing showing. As I think there may be multiple results. And I want a safer solution.
well thanks everyone, I didn't expect such a great response.
I was interested to see how this would be solved, but apparently the following line works
aTags[i].value='123456789';
I suppose anything with the word value is seen as a value field if the exact 'value' attribute can't be found.
Thanks flash, attr might work for this also I suppose.
var myInput = $('input[name="password"]').setAttribute('data-value','12345678');
alert(myInput.getAttribute('data-value'));
Try this
Since you are using jQuery already you can use the attr() method to get the value of the specified attribute.
var myInput = $('input[data-value]').attr("data-value","12345678");
console.log(myInput.attr('data-value'))
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" data-value="">
var myInput = $('input[name="password"]').attr('data-value','12345678');
alert(myInput.attr('data-value'));
Try something like this
I hope it will help.
const setAttribute = (attr, val) => input => {
return input.setAttribute(attr, val)
}
window.addEventListener("load", () => {
const searchValue = "1231"
const selector = `input[value='${searchValue}']`;
const inputs = Array.from(document.querySelectorAll(selector));
inputs.map(setAttribute("data-value", "1231231"))
})
<input value="1231" />
<input value="1231" />
<input value="aaa" />
with jQuery you can access the data attributes directly, but you must cycle through them as there may be more than one:
$.each($('input[data-value='']'),function(){
$(this).data('value','12345678');
});
or, if the input field is just one, use an id:
<input type='password' id="pwd" data-value="" />
and
$('#pwd').data('value','12346578');
<input /> is a self closed element so it will not have textContent attribute. But, yes, in some browsers it will work if you type <input>text content</input>, but in others it won't work.
What i recommend is to keep that value in an attribute right on the input. Follow the example bellow.
Documentation:
About textContent: https://developer.mozilla.org/en-US/docs/Web/API/Node/textContent
Self Closing elements: https://developer.mozilla.org/en-US/docs/Glossary/Empty_element
<input type="text" data-textcontent="password"/>
JS
var aTags = document.getElementsByTagName('input');
var found;
var searchText = 'password';var found;
for (var i = 0; i < aTags.length; i++)
{
console.log(aTags[i].getAttribute('data-textcontent'));
if (aTags[i].getAttribute('data-textcontent') == searchText){
aTags[i].setAttribute('data-value','123456789');
found = aTags[i].getAttribute('data-value');
break;
}
}
console.log(found);

getElementByID.readOnly in array

Im trying to create a list of input ID's and use it in array, to make them readOnly - but the result is error -> "cannot read property 'readOnly' of null".
Can you give me a hint what I should change?
script language="javascript" type="text/javascript">
$(document).ready(function () {
$(function(){
var index, len;
$.get('/SomeList.txt', function(data){
var SomeList = data.split('\n');
for (index = 0, len = SomeList.length; index < len; index++) {
document.getElementById(SomeList[index]).readOnly = true;
}
});
});
});
</script>
and txt file contains name of input ID:
TextFieldName
TextFieldEmail
TextFieldDepartment
TextFieldOffice
Assuming you have some elements with the given IDs you must check if the element exists first before doing
document.getElementById(SomeList[index]).readOnly = true;
so replace that line with
var myElement = document.getElementById(SomeList[index]);
if(myElement == null) {
return;
}
myElement.readOnly = true;
That should work like following example where the IDs come from an array and the second one will not mach because of xxxxx so it's not readonly. But all the others are.
var dataArray = [
'TextFieldName',
'TextFieldEmailxxxxx',
'TextFieldDepartment',
'TextFieldOffice'
];
dataArray.forEach(function(id){
var myElement = document.getElementById(id);
if(myElement == null) {
return;
}
myElement.readOnly = true;
});
<input id="TextFieldName" type="text">
<input id="TextFieldEmail" type="text">
<input id="TextFieldDepartment" type="text">
<input id="TextFieldOffice" type="text">
var id_array=["email","country"];
for (i = 0; i <id_array.length; i++) {
document.getElementById(id_array[i]).readOnly = true;
}
Email: <input type="text" id="email" value="test#mail.com"><br>
Country: <input type="text" id="country" value="Norway" >
it is working fine in my case.
i think there may be whitespace in your array items because your are reading them from file.so try to trim array items.
and make sure you assign id's to input elements

Javascript getElementsByName() for changing names

I have a automatically rendered HTML form which uses a index for the input fields.
for quantity:
<input id="id_orderline_set-0-orderline_quantity" name="orderline_set-0-orderline_quantity" onkeyup="orderlineTotal()" type="number" value="120">
for product price;
<input id="id_orderline_set-0-orderline_product_price" name="orderline_set-0-orderline_product_price" onkeyup="orderlineTotal()" type="number" value="22">
for total line price;
<input id="id_orderline_set-0-orderline_total_price" name="orderline_set-0-orderline_total_price" tag="orderline_total_price" type="number" value="2640">
For the following lines the index of the id and name are increased, only quantity example shown;
<input id="id_orderline_set-1-orderline_quantity" name="orderline_set-1-orderline_quantity" onkeyup="orderlineTotal()" type="number" value="55">
I would like to use the following JavaScript to calculate the total line price;
function orderlineTotal()
{
var orderlineTotalPrice = 0;
var theForm = document.forms["orderform"];
var orderlineQuantityField = theForm.getElementsByName["orderline_quantity"];
var orderlineProductPriceField = theForm.getElementsByName["orderline_product_price"];
var orderlineTotalPriceField = theForm.getElementsByName["orderline_total_price"];
for (var i = 0; i < orderlineQuantityField.length; i ++) {
orderlineTotalPrice = orderlineQuantityField[i].value * orderlineProductPriceField[i].value;
orderlineTotalPriceField[i].value = orderlineTotalPrice;
}
}
Offcourse this wont work because the name of the elements do not match. Can i lookup the name of the element by using a partial name? If not, how should i loop through the input boxes to calculate the line total?
You tagged jQuery so if you want to use jQuery you can use ends with selector:
$("input[name$='orderline_quantity']")
ends with
there's also
starts with
$("input[name^='id_orderline_set-0']")
and contains
$("input[name*='orderline_']")
Maybe you could use static names. Set the equal input names for inputs of the same type and then use this function:
var elements = document.getElementsByName('name');
for (var i=0; i<elements.length; i++) {
doSomething(elements[i]);
}
where name matches name of input.
Example
Instead of:
name="orderline_set-0-orderline_total_price"
use:
name="orderline_total_price"
and then:
var orderlineTotalPriceField = theForm.getElementsByName["orderline_total_price"];
and so on...

Javascript select all HTML input fields with array style name

I have a form that I am building and would like to have a javascript to select and manipulate all of the fields that are within the named array:
<input type="text" name="location[street]" value required />
<input type="text" name="location[city]" value required />
<input type="text" name="location[zip]" value required />
<input type="text" name="location[state]" value required />
How can I build a selector for javascript to toggle all of the elements disabled state?
Jquery is possible but not preferred. I would prefer a method that would work without libraries - such as document.getElementsByName().
I believe that querySelectorAll doesn't have support for a selector to get an element by an attribute, like jQuery would be input[name^="location"](docs). So, try this:
var els = document.querySelectorAll('input');
for (var i = 0; i < els.length; i++)
{
if (els[i].name.indexOf("location") > -1)
{
els[i].disabled = true;
}
}
Fiddle. I will be glad to hear that I'm wrong and there is a way for doing this only using a selector.
Anyway, you can use the fieldset and make your code more semantic by disabling only the fieldset, if you like: Fiddle.
UPDATE
In order to disable all textarea and select elements as well, just include those tags on the selector:
var els = document.querySelectorAll('input, textarea, select');
Fiddle
Alternative to queryselector would be getElementsByTagName
var i;
var inputs = document.getElementsByTagName("input");
for (i = 0; i < inputs.length; ++i) {
var name = inputs[i].getAttribute("name");
if(name.indexOf("location") > -1)
{
inputs[i].disabled = true;
console.log(name);
}
}
link to JSFIddle

Set the value of a Javascript input hidden field to that of a value entered in another input text field

I have an input text field (name: qtyText) to which a user enters a value. I would like to set this value as the value for another hidden field (name: qtyTextHidden) using JavaScript. How can I go about it?
HTML
<input name = "qtyText" type = "textbox" size = "2" value = "" />
<input type="hidden" value = "" name="qtyTextHidden"/>
My efforts to set the field value using JS work, but I am unable to send the value to the servlet. So I am attempting to directly set the value using a function and then try and send it to the servlet. I would like to have a value = someJSFunction() kind. The function needs to trigger upon "onChange" in the "qtyText" input field.
Using jQuery:
$(document).ready(function() {
$('input:text[name="qtyText"]').keyup(function() {
$('input:hidden[name="qtyTextHidden"]').val( $(this).val() );
});
});
Using JavaScript:
window.onload = function() {
if(document.readyState == 'complete') {
document.getElementsByTagName('input')[0].onkeyup = function() {
document.getElementsByTagName('input')[1].value = this.value;
};
}
}:
I'd suggest:
function updateHidden(valueFrom, valueTo) {
valueTo.value = valueFrom.value;
}
var inputs = document.getElementsByTagName('input'),
textInputs = [],
hiddenInputs = [],
refersTo;
for (var i = 0, len = inputs.length; i < len; i++) {
switch (inputs[i].type) {
case 'hidden':
hiddenInputs.push(inputs[i]);
break;
case 'text':
default:
textInputs.push(inputs[i]);
break;
}
}
for (var i = 0, len = textInputs.length; i < len; i++) {
refersTo = document.getElementsByName(textInputs[i].name + 'Hidden')[0];
if (refersTo !== null) {
textInputs[i].onchange = function () {
updateHidden(this, document.getElementsByName(this.name + 'Hidden')[0]);
};
}
}
JS Fiddle demo.
Incidentally: there is no type="textbox". At all. Ever. Anywhere in HTML, not even in HTML 5: it's type="text". The only reason it works with type="textbox" is because browsers are ridiculously forgiving and, if the type isn't understood, it defaults to type="text".
To set the value of the hidden field the easiest way is to use the javascript function that to pass three parameters from, to, and form names:
<script type="text/javascript">
function someJSFunction(form, from, to){
var el_from=form[from], el_to=form[to];
el_to.value=el_from.value;
return el_to.value;
}
</script>
<form name="myform">
<input name = "qtyText" type = "textbox" size = "2" value = "" onchange="someJSFunction(myform, 'qtyText', 'qtyTextHidden')"/>
<input type="hidden" value = "" name="qtyTextHidden"/>

Categories

Resources