getElementByID.readOnly in array - javascript

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

Related

How do I get the Onkey Function to copy the value of a input textfield to the other 3 textfields

This is the Java Script I'm using. I can enter in the proceduredate and it copies to proceduredate2 but not 3 and 4--Same with Procedure
function copyTextAreaValue(id, ids) {
// get source element
var sourceElement = document.getElementById(id);
if(sourceElement) {
// copy to destination elements
var destIds = ids.split(',');
for(i=0; i<destIds.length; i++) {
var destEle = document.getElementById(destIds[i]);
if(destEle) {
destEle.value = sourceElement.value;
} else {
console.log('no dest element ' + destIds[i]);
}
}
}
}
Link to JSFiddle with full code
Your question id not clear to me. However, all I understood is you want to copy text from your current text input to other three text input. If that is true, then you can have your solution here. Please, checkout the snippet below.
let el = document.getElementById('field_1');
function copyTextValue() {
let elVal = el.value;
document.getElementById("field_2").value = elVal;
document.getElementById("field_3").value = elVal;
document.getElementById("field_4").value = elVal;
}
copyTextValue();
el.oninput = copyTextValue;
el.onchange = copyTextValue;
Today's Date: <input id="field_1" value=""/><br/>
Procedure Date: <input id="field_2" value=""/> <br/>
Date of Procedure: <input id="field_3" value=""/> <br/>
Surgery Date: <input id="field_4" value=""/> <br/>
function copyTextfieldValue(id, ids) {
// get source element
var sourceElement = document.getElementById(id);
if(sourceElement) {
// copy to destination elements
var destIds = ids.split(',');
for(i=0; i<destIds.length; i++) {
var destEle = document.getElementById(destIds[i]);
if(destEle) {
destEle.value = sourceElement.value;
} else {
//console.log('no dest element ' + destIds[i]);
}
}
}
}
<input id="t1">
<input id="t2">
<input id="t3">
<input id="t4">
<input type="button" value='copy' onclick="copyTextfieldValue('t1','t2,t3,t4');">
Your code seems to work fine. See the snippet.

JavaScript form same values

How can I make a form so they cannot repeat the same values in the Input?
I tried a way like:
var text1 = document.getElementById('num1').value;
var text2 = document.getElementById('num1').value;
var textform = [text1,text2];
if (
text1 == text2 ||
text2 == text1
) {
alert("repeated numbers");
return false;
}
But this is gets me into two troubles:
- If I put no value, it will say: Repated Numbers
- If I want to make this for 100 form values, it takes a lot of code
You could give all of your text elements the same class, and grab their values by class name to simplify building the array of text values.
<input type="text" class="checkDupe" id="input1" />
<input type="text" class="checkDupe" id="input2" />
Then grab their values in javascript
var checkDupes = document.getElementsByClassName('checkDupe');
var textArray = [];
for(var i = 0; i < checkDupes.length; i++){
textArray.push(checkDupes[i].value);
}
Now that we have an array of values that they entered, check to see if any of them repeat by sorting the array, and seeing if any two elements side-by-side are the same.
textArray.sort();
var dupes = false;
for(var i = 0; i < textArray.length; i++){
if(textArray[i] === textArray[i + 1]) dupes = true;
}
If we find any duplicates, let the user know.
if(dupes) alert('Repeated numbers!');
You could do something like this:
var text1 = document.getElementById('num1').value;
var text2 = document.getElementById('num2').value;
var textform = [text1, text2];
var seen = {};
textform.forEach(function(value) {
if (seen[value]) {
alert('Bad!');
}
seen[value] = true;
});
In the code above, we loop over each value in the array. The first time we encounter it, we push it into a map. Next time (if) we hit that value, it will exist in the map and it will tell us we've seen it before.
If you give all the input's a common class then you quickly loop through them.
The HTML:
<input type="text" name="num1" class="this that number"></input>
<input type="text" name="num2" class="this number"></input>
<input type="text" name="num3" class="that number"></input>
<input type="text" name="num4" class="number"></input>
<input type="text" name="num5" class=""></input> <!-- we don't want to check this one -->
<input type="text" name="num6" class="number that this"></input>
<input type="text" name="num7" class="this that number"></input>
The JavaScript:
// get all the inputs that have the class numbers
var ins = document.querySelectorAll("input.numbers");
// a tracker to track
var tracker = {};
// loop through all the inputs
for(var i = 0, numIns = ins.length; i < numIns; ++i)
{
// get the value of the input
var inValue = ins[i].value.trim();
// skip if there is no value
if(!inValue) continue;
// if the value is already tracked then let the user know they are a bad person
// and stop
if(tracker[inValue])
{
alert("You are a bad person!");
return;
}
// track the value
tracker[inValue] = true;
}
You could also enhance this to let the user know which inputs have duplicate values:
// get all the inputs that have the class numbers
var ins = document.querySelectorAll("input.numbers");
// a tracker to track
var tracker = {};
// loop through all the inputs
for(var i = 0, numIns = ins.length; i < numIns; ++i)
{
// get the value of the input
var inValue = ins[i].value.trim();
// skip if there is no value
if(!inValue) continue;
// if the value is already tracked then error them
if(tracker[inValue])
{
// mark the current input as error
ins[i].className += " error";
// mark the first found instance as an error
ins[tracker[inValue]].className += " error";
}
// save the index so we can get to it later if a duplicate is found
tracker[inValue] = i;
}
Here's a way of doing it that automatically picks up all the text inputs in your document and validates based on what you're looking for. Would be simple enough to expose the valid value and make this the validation handler (or part of one) that handles a form submission.
<meta charset="UTF-8">
<input id="num1" type="text" value="foobar1">
<input id="num2" type="text" value="foobar2">
<input id="num3" type="text" value="foobar3">
<input id="num4" type="text" value="foobar4">
<input id="num5" type="text" value="foobar5">
<button onClick="checkValues();">Validate</button>
<script>
function checkValues() {
var inputs = document.getElementsByTagName('input');
arrInputs = Array.prototype.slice.call(inputs);
var valid = true;
var valueStore = {};
arrInputs.forEach(function(input) {
if (input.type == 'text') {
var value = input.value.toUpperCase();
if (valueStore[value]) {
valid = false;
} else {
valueStore[value] = true;
}
}
});
if (valid) {
alert('Valid: No matching values');
} else {
alert('Invalid: Matching values found!');
}
}
</script>
With jquery you can iterate directly over the inputs.
<form>
<input type="text" >
<input type="text" >
<input type="text" >
<input type="text" >
<input type="text" >
<input type="text" >
<button>
TEST
</button>
</form>
function checkValues(){
var used = {};
var ok = true;
$('form input[type="text"]').each(function(){
var value = $(this).val();
if(value !== ""){
if(used[value] === true){
ok = false;
return false;
}
used[value] = true;
}
});
return ok;
}
$('button').click(function(event){
event.preventDefault();
if(!checkValues()){
alert("repeated numbers");
};
});
https://jsfiddle.net/8mafLu1c/1/
Presumably the inputs are in a form. You can access all form controls via the form's elements collection. The following will check the value of all controls, not just inputs, but can easily be restricted to certain types.
If you want to include radio buttons and checkboxes, check that they're checked before testing their value.
function noDupeValues(form) {
var values = Object.create(null);
return [].every.call(form.elements, function(control){
if (control.value in values && control.value != '') return false;
else return values[control.value] = true;
});
}
<form id="f0" onsubmit="return noDupeValues(this);">
<input name="inp0">
<input name="inp0">
<input name="inp0">
<button>Submit</button>
</form>
For old browsers like IE 8 you'll need a polyfill for every.
You can simply get all inputs iterate them twice to check if they are equals
var inputs = document.getElementsByTagName('input');
for (i = 0; i < inputs.length; i++) {
for (j = i + 1; j < inputs.length; j++) {
if (inputs[i].value === inputs[j].value) {
console.log('value of input: ' + i + ' equals input: ' + j);
}
}
}
<input value="56" />
<input value="12" />
<input value="54" />
<input value="55" />
<input value="12" />

Get array text filed value via javascript

in my process text filed in array i need to get the value via javascript but my code is not working my code following
<input type="text" id="itemid[]" name="itemid[]" class="span12"/>
and javascript code is
function getstock()
{
var itemidarr=document.getElementById('itemid[]');
if(itemidarr!= null)
{
alert(itemidarr.length);
}
}
any other solution for this
The IDs can't contain brackets, these: [], so:
<input type="text" id="itemid1" name="itemname1" class="span12"/>
<input type="text" id="itemid2" name="itemname1" class="span12"/>
<input type="text" id="itemid3" name="itemname1" class="span12"/>
Then you have to loop through the IDs:
function getstock()
{
for(var i=1; i<=3; i++){
var itemidarr=document.getElementById("itemid"+i);
if(itemidarr!= null) alert(itemidarr.length);
}
}
The id attribute here cannot contain [ ].
Put your textboxex in "fieldset tag"
Like:
<fieldset id="field">
//Put you text boxes here<input type='text'>
</fieldset>
Access these by:
document.getElementById("list....").getElementsByTagName("input")[indexoftext];
indexoftext is the text box you wan to choose.
Hope it helps!
you can try something like this below
<input type="text" id="itemid" name="itemid" class="span12"/>
function getstock()
{
var itemidarr = document.getElementsByName('itemid');
for(var i = 0; i < itemidarr.length; i++){
var item=document.getElementsByName('itemid')[i].value;
if(item!= null)
{
alert(item);
}
}
}
You can't make an array to fill in an input text, only for input like radio or checkbox.
Text input only accept a single string.
function getstock() {
var a = [];
jQuery.each(this, function(i, field){
a.push($.trim(field.value));
});
return a;
}
can u use this code
i got the result
function getstock1()
{
alert("test");
var itemidarr = document.getElementsByName('itemid[]');
for (var i = 0; i < itemidarr.length; i++)
{
alert(itemidarr[i].value);
}

JavaScript - get value from multiple inputs in an array

I am trying to get the value from muliple inputs with the same id in an array.
I already used the forum, but haven't find a solution for me.
Exmaple
<input type="hidden" value="'+image_url+'" name="webcampics[]" id="webcampics">
<input type="hidden" value="'+image_url+'" name="webcampics[]" id="webcampics">
<input type="hidden" value="'+image_url+'" name="webcampics[]" id="webcampics">
<input type="hidden" value="'+image_url+'" name="webcampics[]" id="webcampics">
var elem = document.getElementById("webcampics");
var names = [];
for (var i = 0; i < elem.length; ++ i) {
names += elem[i]+'|';
}
var webcamval = names;
You shouldn't have elements with identical id's within the document. ID's have to be unique throughout your entire markup, by specification. If you do it anyways, methods like document.getElementById will only match the very first occurence for instance.
Use a class instead of ids.
<input type="hidden" value="'+image_url+'" name="webcampics[]" class="webcampics">
<input type="hidden" value="'+image_url+'" name="webcampics[]" class="webcampics">
<input type="hidden" value="'+image_url+'" name="webcampics[]" class="webcampics">
<input type="hidden" value="'+image_url+'" name="webcampics[]" class="webcampics">
var inputs = document.getElementsByClassName( 'webcampics' ),
names = [].map.call(inputs, function( input ) {
return input.value;
}).join( '|' );
Demo: http://jsfiddle.net/QgJrq/
What you are asking for is wrong very wrong, it is recommended IDs should be unqiue, but for learners sake here's what you would do
var elem = document.getElementsByTagName("input");
var names = [];
for (var i = 0; i < elem.length; ++i) {
if (typeof elem[i].attributes.id !== "undefined") {
if (elem[i].attributes.id.value == "webcampics") {
names.push(elem[i].value);
}
}
}
var webcamval = names;
http://jsfiddle.net/5vamG/
Due to someone down voting after giving a full explanation why the above mentioned method is wrong, however does exactly what youve asked for, here's the correct method.
change all the inputs id to class
var elem = document.getElementsByClassName("webcampics");
var names = [];
for (var i = 0; i < elem.length; ++i) {
if (typeof elem[i].value !== "undefined") {
names.push(elem[i].value);
}
}
}
var webcamval = names;
http://jsfiddle.net/5vamG/1/
You shouldn't have more than one element with the same id.
getElementById returns exactly one element; use getElementsByName which will return the list you seek.

How do I simplify this jquery script?

I have an ASP.NET web forms project that I am trying to implement auto-tabbing in. I'm new to jquery, but I found a code snippet online to do auto-tabbing, and I want to use it to autotab multiple groups of textboxes.
For example:
Textbox1 -> Textbox2 -> Textbox3
Textbox4 -> Textbox5 -> Textbox6
But not:
Textbox3 -> Textbox4
Hope that makes sense. Anyway, I have the following code:
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.5.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
$(".autotab").keyup(function () {
if ($(this).attr("maxlength") == $(this).val().length) {
var index = $(".autotab").index(this);
var item = $($(".autotab")[++index]);
if (item.length > 0)
item.focus();
}
});
$(".autotab2").keyup(function () {
if ($(this).attr("maxlength") == $(this).val().length) {
var index = $(".autotab2").index(this);
var item = $($(".autotab2")[++index]);
if (item.length > 0)
item.focus();
}
});
});
</script>
<input name="tbOne" type="text" maxlength="3" id="tbOne" class="autotab" />
<input name="tbTwo" type="text" maxlength="3" id="tbTwo" class="autotab" />
<input name="tbThree" type="text" maxlength="4" id="tbThree" class="autotab" />
<input name="tbFour" type="text" maxlength="3" id="tbFour" class="autotab2" />
<input name="tbFive" type="text" maxlength="3" id="tbFive" class="autotab2" />
<input name="tbSix" type="text" maxlength="4" id="tbSix" class="autotab2" />
How can I refactor the copy/pasted code into a single function?
A more general solution, that doesn't require that you use one class per group:
// loop through adjacent pairs
$.fn.eachPair = function(f) {
for(var i = 0, j = 1; j < this.length; i = j++)
f.call(this[i], this[j]);
}
$.fn.autotab = function() {
this.eachPair(function(next) {
// add an event handler to focus the next field
$(this).keyup(function() {
if($(this).attr("maxlength") == $(this).val().length)
$(next).focus();
});
});
}
$(document).ready(function () {
$(".autotab").autotab();
$(".autotab2").autotab();
});
As a side note, the $($(".autotab2")[++index]) in your code would have been better written as $(".autotab2").eq(index + 1)
You can limit the element by passing in a selector into .next() - this is assuming you have one class assigned to your inputs only and they are all siblings.
// get all inputs with class that start with autotab
$("input[class^=autotab]").keyup(function() {
var $el = $(this);
// get nextfield with same class
var nextField = $el.next('.'+$el.attr('class'));
if($el.attr("maxlength") == $el.val().length){
// if true - give next field with same class focus
$el.next().focus();
}
});​
http://jsfiddle.net/JaVaR/
Or if they aren't guaranteed siblings.. you can use .eq() to get current index and increment by one. This will get the collection of elements that match the current elements class, then get the index of the current to find the next field
$("input[class^=autotab]").keyup(function() {
var $el = $(this);
// gets all inputs with same class
var $inp = $('.'+$el.attr('class'));
// gets next input with same class
var nextField = $inp.eq($inp.index(this)+1);
if($el.attr("maxlength") == $el.val().length){
nextField.focus();
}
});​
http://jsfiddle.net/L4MEP/

Categories

Resources