Disable many fields by name javascript - javascript

This is my question:
I got an jsp page, this jsp has many text fields like this:
<html:text property="cicPF" maxlength="9" style="text-transform: uppercase;" onfocus="disableIfeFields()"/>
So I want to disable some of this text fields when the focus it's in a specific field
But no one of this fields has "id" label, and I can't modify it to include it.
May I disable the fields usig their given names, no one of this repeats the same name.
for example with a function like this:
function disableIfeFields(){
document.getElementsByName("numIdentificacionPF").disabled = true;
}
thanks

You need to loop through the list and disable all the fields you want that way, used input to show example:
function disableIfeFields() {
document.getElementsByName("numIdentificacionPF").forEach((e) => {
e.disabled = true;
});
}
<html:text property="cicPF" maxlength="9" style="text-transform: uppercase;" />
<input onfocus="disableIfeFields()" type="text" name="fname">
<input type="text" name="numIdentificacionPF">
<input type="text" name="numIdentificacionPF">
<input type="text" name="numIdentificacionPF">
<input type="text" name="numIdentificacionPF">
<input type="text" name="numIdentificacionPF">

Maybe like this:
function disableIfeFields(){
document.querySelectorAll('[property="cicPF"]')[0].disabled = true;
}
disableIfeFields();
<input type="text" property="cicPF" maxlength="9" style="text-transform: uppercase;" onfocus="disableIfeFields()"/>

Hopefully the following should help. Because the selection result is a list of elements you will have to loop through the results.
Please note that since you said no input repeats the same name, I'm using querySelectorAll, which might be a more suitable method after all…
var inputs = document.querySelectorAll('input[type="text"]');
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].id === 'label') {
continue;
}
inputs[i].disabled = true;
}

Related

How to change the value of all input boxes at once by looping after inputting the value in the input box in javascript?

I am a beginner in javascript ~ I
have a requirement, I hope I can enter some numbers in the input box A at the bottom, after pressing send ~
I can change all the values ​​in the top five input boxes to the input box A. It feels like it can be done using forEach, but I don't know how to start making changes, I hope everyone can help, thank you.
let jsInput = document.querySelector('#js-input');
let jsSend = document.querySelector('#js-send');
jsSend.addEventListener('click', function() {
console.log(jsInput.value)
})
<input type="text" value="123">
<input type="text" value="666">
<input type="text" value="345">
<input type="text" value="1000">
<h2>I want to change all this numbe</h2>
A <input type="text" id="js-input"><button id="js-send">send</button>
You can do it by adding a class to your other inputs that you want to change and then use getElementsByClassName to get them all and change their value inside a for loop since this return an array
let jsInput = document.querySelector('#js-input');
let jsSend = document.querySelector('#js-send');
jsSend.addEventListener('click', function() {
const inputs = document.getElementsByClassName('inputc');
for (let i = 0; i < inputs.length; i++) {
inputs[i].value=jsInput.value;
}
})
<input class="inputc" type="text" value="123">
<input class="inputc" type="text" value="666">
<input class="inputc" type="text" value="345">
<input class="inputc" type="text" value="1000">
<h2>I want to change all this numbe</h2>
A <input type="text" id="js-input"><button id="js-send">send</button>

JS input validation submit disabled for separate instances

I need each instance of input and submit to operate independently. What is the best way to handle multiple instances where each submit is connected to it's own set of inputs?
Since they are unrelated, would data-attributes be the best solution?
$(document).ready(function() {
validate();
$('input').on('keyup', validate);
});
function validate() {
var inputsWithValues = 0;
var myInputs = $("input:not([type='submit'])");
myInputs.each(function(e) {
if ($(this).val()) {
inputsWithValues += 1;
}
});
if (inputsWithValues == myInputs.length) {
$("input[type=submit]").prop("disabled", false);
} else {
$("input[type=submit]").prop("disabled", true);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="item1">
<div><input type="text" name="name" autocomplete="off" required/></div>
<input type="submit" value="Submit 1" />
</div>
<div class="item2">
<div><input type="text" name="name" autocomplete="off" required/></div>
<div><input type="text" name="name" autocomplete="off" required/></div>
<input type="submit" value="Submit 2" />
</div>
I think your intuition about using data attributes works great here.
var allButtons = document.querySelectorAll("input[type=submit]");
allButtons.forEach(button => {
button.addEventListener("click", () => {
var inputSet = button.getAttribute("data-input-set");
var inputs = document.querySelectorAll("input[type='text'][data-input-set='" + inputSet + "']");
});
});
In the following code, when an input button is pressed, it will fetch all the inputs with the corresponding "input-set" tag.
Preferred way
I think best solution would be use form -tag as it is created for just this use case HTML Forms.
<form id="form-1">
<input type="text"/>
<input type="submit>
</form>
<form id="form-2">
<input type="text"/>
<input type="submit>
</form>
You can also bind custom Form on submit event handlers and collect form data this way.
$('#form-1').on('submit', function(event){
event.preventDefault(); // Prevent sending form as defaulted by browser
/* Do something with form */
});
Possible but more bolt on method
Alternative methods to this would be to create your own function's for collecting all relevant data from inputs and merge some resonable data object.
I would most likely do this with giving desired class -attribute all inputs I would like to collect at once eg. <input type="text" class="submit-1" /> and so on. Get all elements with given class, loop through all them and save values into object.
This requires much more work tho and form -tag gives you some nice validation out of the box which you this way have to do yourself.

Disable button unless specific fields have values

I have an ASPX form and I need to disable the submit button if any one of six specific fields are empty. I'm trying to do this via Javascript or jQuery, but so far I can only find examples of either a single field on the form being empty, or ALL fields on the form. In my case, I don't care about several fields - only the six specific ones.
So basically, I have six conditions and one action. I found one example, but it was stringing together six different IF statements. I'd like to find a more streamlined way if possible. So, for example, I might do THIS for a single field... but how to do it for field2, field3, field4, etc. as well?
$(document).ready(function(){
$('#submit_btn').prop('disabled',true);
$('#field1').keyup(function(){
$('#submit_btn').prop('disabled');
})
});
Using Javascript or jQuery, what's the most efficient way to disable an input button if any of six input fields is blank?
You can add the same class name to all the elements and then do a validation foreach class element. Like in below code, i added the same class name to all the input for which the validation is required using class="valid" and then use the jquery class selector and the keyup method that you used to control the state of the button.
(function() {
$('.valid').keyup(function() {
var isEmpty = false;
$('.valid').each(function() {
if ($(this).val() == '') {
isEmpty = true;
}
});
if (isEmpty) {
$('#button1').attr('disabled', 'disabled');
} else {
$('#button1').removeAttr('disabled');
}
});
})()
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
1<input type="text" class="valid" /><br />
2<input type="text" class="valid" /><br />
3<input type="text" class="valid" /><br />
4<input type="text" class="valid" /><br />
5<input type="text" class="valid" /><br />
6<input type="text" class="valid" /><br />
<input type="button" id="button1" value="Test Me!" disabled="disabled" />
</form>
If your requirements will allow it, you can use HTML 5 field validation. The browser will not allow the form to submit.
<form>
<label for="choose">Foo</label>
<input name="bar" required>
<input type="submit" /> <!-- <--- This will generate an error message if the user clicks it when the field is empty -->
</form>
You have the start of it correct; create an array with six variables, one for each of the fields, and create a new function to validate everything that is called on each keyup. So you would have
var[] array
$('#field1').keyup(function() {
array[0] = $('#field1').val();
validate();
}
${'#field2').keyup(function() {
array[1] = $('#field2').val();
validate();
}
...create one each for each field
function validate() {
for (var i = 0; i < array.length; i++) {
if(!arrays[i]) {
$('#submit_btn').prop('disabled');
return;
}
}
$('#submit_btn').prop('enabled'):
}
What this does is it listens to the fields for changes and updates the array. A blank value is falsy so you can just go through the array and disable the button if it's blank or null or something. Break out of the for loop in that case; you don't care about whatever else. If nothing disables the button and breaks the for loop then it's valid and the button is enabled.
This approach is useful because it's easily extendable. You can just push extra things into the array if you want to check them without rewriting the validation function.
This assumes you do not want to just use standard form validation and do it manually.
Add a common class to each of the required inputs. Then check the length of that object against the length of a filtered object where value is not empty. Then you can use that condition to set the prop value of the button to true/false.
http://api.jquery.com/filter/
JQuery:
$('form .required-valid').on('input paste change', function() {
var $required = $('form .required-valid');
//filter required inputs to only ones that have a value.
var $valid = $required.filter(function() {
return this.value != '';
});
//set disabled prop to false if valid input count is != required input count
$('#submit_btn').prop('disabled', $valid.length != $required.length);
});
HTML:
<form>
<label>Field1</label>
<input type="text" id="field1" class="required-valid" />
<label>Field2</label>
<input type="text" id="field2" class="required-valid" />
<label>Field3</label>
<input type="text" id="field3" class="required-valid" />
<label>Field4</label>
<input type="text" id="field4" class="required-valid" />
<label>Field5</label>
<input type="text" id="field5" class="required-valid" />
<label>Field6</label>
<input type="text" id="field6" class="required-valid" />
<label>Field7</label>
<input type="text" id="field7" class="not-required" placeholder="not required" />
<button id="submit_btn" disabled>
Submit
</button>
</form>
Example:
https://jsfiddle.net/SeanWessell/q2msc80L/
$(document).ready(function() {
$('#submit_btn').prop('disabled', true);
$('#field1').keyup(function() { // on keyup
var value = $(this).val(); // retrieve the value of the input
if (value.length == 0) // if the value's length is 0 (empty)
$('#submit_btn').prop('disabled', true); // disable the button
else // if not
$('#submit_btn').prop('disabled', false); // enable it
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input id="field1"/>
<input id="submit_btn" type="submit"/>
</form>
Just note that the form can be submitted using enter key, so instead of checking on every keyup, it would be better if you check onsubmit instead.

use same value on 2 inputs on keyup if first one is originaly empty

I have 2 fields in a form Name and Company and I want Name to dynamically get the Company value while it's typed (only if Name is empty when you start imputing Company) and i'm not finding out the best way to achieve this.
for example purposes the HTML is:
<form>
...
<input type="text" id="Name" name="Name" value="">
<input type="text" id="Company" name="Name" value="">
...
</form>
i tried:
$('#Company').on('keyup', function(){
var str = $('#Company').val();
str = str.substring(0, str.length - 1);
if($('#Name').val().length <= 0 || $('#Name').val() == str){
$('#Name').val($('#Company').val());
}
});
and it works to some extent, if you type in too quickly it stops assuming #Name and #Company had the same value before last keyup
I also thought about doing on Company blur and it'll probably work, but that is not the user experience i was wanting to achieve.
This would probably be easier using Angular.js or the likes of that, but using that now is not an option.
Something like this, adding a class that is removed on input into the name field, otherwise the length check will fail after the first character is copied from the Company field.
$('#Name').addClass('empty').on('input', function() {
$(this).toggleClass('empty', this.value.trim().length === 0);
});
$('#Company').on('input', function() {
$('#Name.empty').val(this.value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form>
Name : <input type="text" id="Name" name="Name" value=""><br>
Comp : <input type="text" id="Company" name="Name" value="">
</form>

Javascript call value from other input

I have the following code:
<form>
<input type="text" id="field1" name="field1" value="first value" />
<input type="text" id="field2" onkeyup="showRSS(this.value, this.alt)" value="" alt="test">
</form>
Within the showRSS() onkeyup function I need to call the value from the first input field (id="field1"). How can I do that?
Use its ID with document.getElementById():
So if you want to pass it as the third argument to showRSS():
<input type="text" id="field2" onkeyup="showRSS(this.value, this.alt, document.getElementById('field1').value)" value="" alt="test">
Or if you want to get it from within showRss():
function showRSS( ... )
{
var field1 = document.getElementById('field1').value;
}
If you want to get the values of specific text boxes you can just iterate them in the function and grab the value of those you want based on their name. First, add a name to the second textbox as well then have such code:
function showRSS() {
var oForm = document.forms[0]; //assuming only one form
var desiredInputNames = { "field1": "", "field2": "" }; //names of elements to read
for (var i = 0; i < oForm.elements.length; i++) {
var element = oForm.elements[i];
if (desiredInputNames[element.name]) {
var value = element.value;
//handle the current value
}
}
}
(Using associative array rather than plain array for better searching)
use the below code to do that...
<form>
<input type="text" id="field1" name="field1" value="first value" />
<input type="text" id="field2" onkeyup="showRSS(this.value, this.alt, this.parentNode.getElementsByName('field1')[0].value)" value="" alt="test">
</form>
if you use field1 as name outside the form tag, it won't create any problem...

Categories