How to add onChange function for all HTML form fields - javascript

My HTML Page has 10 Text Fields.
Currently no onChange EVENT is available for all ten fields.
<input type="text" name="text1" value="1">
<input type="text" name="text2" value="2">
<input type="text" name="text3" value="3">
<input type="text" name="text4" value="">
<input type="text" name="text5" value="">
<input type="text" name="text6" value="">...
Now, I want to add onChange Function in all fields whose field is of input type.
How do I add onChange or onBlur even in my JS section?
In onChange function, I will call ajax function which will validate whether the field has Hacking Keywords.
So my question is:
How do I add onChange function for all form fields. My field should dynamically be like below:
<input type="text" name="text1" value="1" onChange="javascript:fnName" onBlur="javascript:fnName" >
<input type="text" name="text2" value="2" onChange="javascript:fnName" onBlur="javascript:fnName" >
<input type="text" name="text3" value="3" onChange="javascript:fnName" onBlur="javascript:fnName" >
<input type="text" name="text4" value="" onChange="javascript:fnName" onBlur="javascript:fnName" >
<input type="text" name="text5" value="" onChange="javascript:fnName" onBlur="javascript:fnName" >
<input type="text" name="text6" value="" onChange="javascript:fnName" onBlur="javascript:fnName" >
<input type="text" name="text7" value="" onChange="javascript:fnName" onBlur="javascript:fnName" >

This can be achieved with vanilla JavaScript as zvona suggests.
Here is a simple loop to mock an HTML5 placeholder. <<DEMO>>
var prompt = 'Type something here';
var textFields = document.querySelectorAll('input[name^="text"]');
var index = 0;
for (index = 0; index < textFields.length; ++index) {
var textField = textFields[index];
textField.addEventListener('change', onChangeHandler);
textField.addEventListener('focus', onFocusHandler);
textField.addEventListener('blur', onBlurHandler);
textField.value = prompt;
console.log(textField);
}
function onChangeHandler() {
// Do something...
}
function onFocusHandler() {
if (this.value === prompt) {
this.value = '';
}
}
function onBlurHandler() {
if (this.value === '') {
this.value = prompt;
}
}

you can try to give change function to your form using
$('.form :input').change(function(e){
$('#log').prepend('<p>Form changed ' + $(e.target).attr('id') + '</p>')
});
Demo1
Demo2

[].forEach.call(document.querySelectorAll("input"), function(input) {
input.addEventListener("change", fnName, false);
input.addEventListener("blur", fnName, false);
});

getElementsByTagname() gets you an array of all input. Interate over them and addEventListener.
Or use jQuery's $('input').on('change'...)

Try something like:
var inputList = document.getElementsByTagName("input");
for(var i=0;i<inputList.length;i++){
inputList[i].onchange = function(){
//function here
}
inputList[i].onblur = function(){
//function here
}
}

Related

remove disabled attribute according input value

function add_option(){
var tot_option=parseInt($('#tot_option').val());
tot_option++;
$('#tot_option').val(tot_option);
var par="'radio"+tot_option+"'";
var opt="<input type='text' id='opt"+tot_option+"' onblur='chk(this.value,'"+par+"')' name='answers[]' style='width:80%;' onfocus='add_option()'> <input type='radio' id='radio"+tot_option+"' required disabled name='canswer' value='"+tot_option+"'><br><br>";
document.querySelectorAll("input[onfocus]").forEach(function(element, index) {
element.removeAttribute("onfocus");
});
$('#new_option').append(opt);
}
function chk(ivalue,rad){
if(ivalue!=''){
$('#'+rad).removeAttr('disabled');
}else{
$('#'+rad).attr('disabled','disabled');
$('#'+rad).removeAttr('checked','checked');
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" style='width:80%;' onblur="chk(this.value,'radio1')" id="opt1" name="answers[]">
<input type="radio" id="radio1" disabled required name="canswer" value="1"><br><br>
<input type="text" id="opt2" onblur="chk(this.value,'radio2')" style='width:80%;' name="answers[]" onfocus="add_option()">
<input type="radio" id="radio2" required disabled name="canswer" value="2"><br><br>
<span id="new_option"></span>
i have multiple input type and one radio button in front of every input i want to remove disabled from radio if my input type have some value if it has no value then add disabled attribute to radio. its working fine in first two input but after that its not working
there were some flaws in your code,
1 you are sending this.value here as a string onblur='chk(this.value,'"+par+"')
2 in this onblur function call there is a problem while sending par as a parameter,
so here I Modified your code a bit and now this is working
function add_option(){
var tot_option=parseInt($('.totalOption').length);
tot_option++;
$('#tot_option').val(tot_option);
var par="'radio"+tot_option+"'";
var onBlur = 'onblur=chk('+ par.toString() +')';
var opt="<input type='text' id='opt"+tot_option+"' class='totalOption' " + onBlur + " name='answers[]' style='width:80%;' onfocus='add_option()'> <input type='radio' id='radio"+tot_option+"' required disabled name='canswer' value='"+tot_option+"'><br><br>";
document.querySelectorAll("input[onfocus]").forEach(function(element, index) {
element.removeAttribute("onfocus");
});
$('#new_option').append(opt);
}
function chk(rad){
if(event.relatedTarget == null)
return;
var SelctedTarget = Number(event.relatedTarget.id[event.relatedTarget.id.length - 1]) - 1;
var ivalue = $('#opt' + SelctedTarget).val();
if(ivalue!=''){
$('#'+rad).removeAttr('disabled');
}else{
$('#'+rad).attr('disabled','disabled');
$('#'+rad).removeAttr('checked','checked');
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" style='width:80%;' onblur="chk('radio1')" id="opt1" class="totalOption" name="answers[]">
<input type="radio" id="radio1" disabled required name="canswer" value="1"><br><br>
<input type="text" id="opt2" class="totalOption" onblur="chk('radio2')" style='width:80%;' name="answers[]" onfocus="add_option()">
<input type="radio" id="radio2" required disabled name="canswer" value="2"><br><br>
<span id="new_option"></span>

Disable textbox if other textbox is not empty in CSS and JavaScript

I have a search form which contains text-boxes. What I want to ask is if textbox1(Hotel (num_rooms)) is not empty then the textbox2(Packages(num_days)) will be disabled or if textbox2(Packages(num_days)) is not empty then the textbox1(Hotel (num_rooms)) will be disabled. Because this search form will leads to different output based on the inputs of an user. If the user tries to put data in textbox1 and submit it, then it will return a lot of recommendations based on the user preferences about hotel same as in packages.
<form action="Filtered-SearchResult.php" method="post">
<div class="SearchForm">
<label id="Form"><h3 style="color:beige; text-align:left;">Search Form</h3></label><br>
<br>
<input type="text" name="location" class="searchtext" id="locate" placeholder="location" onkeyup="LettersOnly(this)" /><br>
<input type="text" name="from_budget" class="searchtext" placeholder="minimum budget" style="width:150px;" onkeyup="NumbersOnly(this)" />
<input type="text" name="to_budget" class="searchtext" placeholder="maximum budget" style="width:150px;" onkeyup="NumbersOnly(this)" /><br>
<input type="text" name="person" class="searchtext" placeholder="no of person" onkeyup="NumbersOnly(this)" /><br>
<input type="text" name="no_of_rooms" class="searchtext" style="width:150px;" placeholder="hotel(num_rooms)" onkeyup="NumbersOnly(this)" />
<input type="text" name="no_of_days" class="searchtext" style="width:150px;" placeholder="Packages(num_days)" onkeyup="NumbersOnly(this)" />
<script>
function LettersOnly(input) {
var regex = /[^a-zA-Z ]/gi;
input.value = input.value.replace(regex, "");
}
function NumbersOnly(input) {
var regex1 = /[^0-9]/gi;
input.value = input.value.replace(regex1, "");
}
</script>
<input type="submit" name="search1" value="Show Prices" id="Prices2" />
</div>
</form>
You can write a change event for no of rooms and no of days like this.
You can add more condition accordingly
$("#no_of_days").change(function(){
if($(this).val() == ""){
$("#no_of_rooms").attr("disabled", false);
}else{
$("#no_of_rooms").attr("disabled", true);
}
});
$("#no_of_rooms").change(function(){
if($(this).val() == ""){
$("#no_of_days").attr("disabled", false);
}else{
$("#no_of_days").attr("disabled", true);
}
});

How to calculate form fields values to update hidden field value?

I want to know how to calculate the input values of the following fields
<input type="text" name="score1" class="auto-sum">
<input type="text" name="score2" class="auto-sum">
<input type="text" name="score3" class="auto-sum">
And update the span text and the hidden field value
TOTAL <span id="amountTotal">0 </span>
<input id="total" type="hidden" name="total" value="">
Thanks in advance
This should do what you want to achieve:
function displaySum () {
var sum = 0;
// iterate over the input fields
$('.auto-sum').each(function () {
var value = $(this).val() || 0;
var number = parseInt(value, 10); // parse the input value to an integer
if (isNaN(number)) {
number = 0;
}
sum += number; // add the value to the sum
});
// set the value of the two elements
$('#amountTotal').text(sum);
$('#total').val(sum);
}
// whenever the value of one of the input fields changes, call the displaySum function
$('.auto-sum').on('change, keyup', displaySum);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="score1" class="auto-sum">
<input type="text" name="score2" class="auto-sum">
<input type="text" name="score3" class="auto-sum">
TOTAL <span id="amountTotal">0 </span>
<input id="total" type="hidden" name="total" value="">
I tried with blur method for after mouseleave from input and check all input values and added ! Then update to wanted element !!
$("input").on("blur",function(){
var total = 0;
$("[type='text']").each(function(){
if($(this).val() != "") {
total += parseInt($(this).val());
}
});
$("#amountTotal").text(total);
$("#total").val(total);
});
Try with query each() function .Use with parseFloat convert the string to number .for real time update do with keyup event
$('.auto-sum').keyup(function(){
var a=0;
$('.auto-sum').each(function(){
a+=parseFloat($(this).val())
})
$('#amountTotal').text(a|0)
$('#total').val(a|0)
console.log($('#total')[0].outerHTML)//its show the hidden field value
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="score1" class="auto-sum" value="2" >
<input type="text" name="score2" class="auto-sum" value="5">
<input type="text" name="score3" class="auto-sum" value="5">
TOTAL <span id="amountTotal" >0 </span>
<input id="total" type="hidden" name="total" value="">
You can use <input type="number" /> inputs to force values entered to be a number.
From there you can call jQuery with the query selector input.auto-sum to get all of the input elements with the class auto-sum
Using the each function you can add the numeric to an accumulator to get the total.
You can then use jQuery with the query selectors needed to set any other elements on the page with the Total value.
function getTotal() {
var total=0;
$('input.auto-sum').each(function(i,e)
{
total += Number($(e).val());
});
$('#amountTotal').text(total);
$('#total').val(total);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Score 1: <input type="number" name="score1" class="auto-sum"><br />
Score 2: <input type="number" name="score2" class="auto-sum"><br />
Score 3: <input type="number" name="score3" class="auto-sum"><br />
TOTAL: <span id="amountTotal">0 </span><br />
<input id="total" type="hidden" name="total" value="">
<input type="button" id="btnTotal" onclick="getTotal()" value="Get Total" />
Please try this one.
$('.auto-sum').on('change',function(){
var totalvalue=0;
$('.auto-sum').each(function(a,b){
totalvalue=totalvalue+parseInt(($(b).val()=='' || isNaN($(b).val()))?0:$(b).val());
});
$('#amountTotal').text(totalvalue);
$('#total').val(totalvalue);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="score1" class="auto-sum">
<input type="text" name="score2" class="auto-sum">
<input type="text" name="score3" class="auto-sum">
TOTAL <span id="amountTotal">0</span>
<input id="total" type="hidden" name="total" value="">
<input type="text" name="score1" class="auto-sum">
<input type="text" name="score2" class="auto-sum">
<input type="text" name="score3" class="auto-sum">
<input type="button" id="calculator" value="Caculate">
$("#calculator").on("click",function (){
var result=0;
var sum_fields=$(".auto-sum");
for(var i=0;i<sum_fields.length;i++){
if(!isNaN(sum_fields[i]) && sum_fields[i]>0){
result += sum_fields[i];
}
}
$("#amountTotal").text(result);
$("#total").val(result);
});
Create array for the fields and loop through them
Check if it not a NaN and more than 0 add them to the result then after the loop attach the result to the hidden field and as a span text
I post this as an answer because the comment areas are to small
At first i think it´s an good idea to write
<input type = "number">
when you don´t want to display the small arrows look at this solution:
https://css-tricks.com/snippets/css/turn-off-number-input-spinners/
the keyup event ist the best way to "live" display the total sum
At last take a look at vue.js
This is the best solution for this scenario.
if you're interested in a pure javascript solution:
All inputs have an oninput event attribute that fires when the input is changed.
You can attach an event handler to the event like so:
<input oninput="updateTotal" />
where updateTotal is a function declared in your script:
function updateTotal { /* code that updates the total */ }
OR if you select the input in your script then you can attach the event handler like this:
selectedInput.oninput = function updateTotal () {
...
}
Here's my implementation that selects all the inputs with the class "auto-sum", assigns the event handler to each of them and updates the code by looping over each input's value attribute:
https://jsfiddle.net/billy_reilly/5dd24v81/2/
function displaySum () {
var sum = 0;
// iterate over the input fields
$('.auto-sum').each(function () {
var value = $(this).val() || 0;
var number = parseInt(value, 10); // parse the input value to an integer
if (isNaN(number)) {
number = 0;
}
sum += number; // add the value to the sum
});
// set the value of the two elements
$('#amountTotal').text(sum);
$('#total').val(sum);
}
// whenever the value of one of the input fields changes, call the displaySum function
$('.auto-sum').on('change, keyup', displaySum);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="score1" class="auto-sum">
<input type="text" name="score2" class="auto-sum">
<input type="text" name="score3" class="auto-sum">
TOTAL <span id="amountTotal">0 </span>
<input id="total" type="hidden" name="total" value="">

HTML form:input calculate 2 fields

I'm using spring mvc for my form which has the tag
<form:input type="number" class="value1" id="value1" path="commandName.object.field1" />
<form:input type="number" class="value1" id="value1" path="commandName.object.field2" />
<input type="text" disabled="disabled" id="result" />
I read some questions in regards to calculations and even found a js fiddle:
http://jsfiddle.net/g7zz6/1125/
how do i calculate 2 input fields and put results in 3rd input field
but it doesn't work when the input tag is form:input. Is it possible to do auto calculation of the 2 form:input fields upon keyin and update the 3rd input?
Here you go
HTML
<input type="text" class="input value1">
<input type="text" class="input value2 ">
<input type="text" disabled="disabled" id="result">
JS
$(document).ready(function(){
$('input[type="text"]').keyup(function () {
var val1 = parseInt($('.value1').val());
var val2 = parseInt($('.value2').val());
var sum = val1+val2;
$("input#result").val(sum);
});
});
Fiddle https://jsfiddle.net/1sbvfzcc/
$(document).ready(function(){
var val1 = +$(".value1").val();
var val2 = +$(".value2").val();
$("#result").val(val1+val2);
});
$('.input').blur(function(){
var val1 = +$(".value1").val();
var val2 = +$(".value2").val();
$("#result").val(val1+val2);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="input value1" value="20">
<input type="text" class="input value2" value="30">
<input type="text" disabled="disabled" id="result">
Please check the code this might help you understand why your code is not working.
You are using document ready function which is not able to get the value as no default value for input box.
I have added a new blur function which will calculate the value on change of input box
Try this your form tag syntax was wrong
$('form').on('keyup' ,'.value1', function(){
var k=0;
$('.value1').each(function(){
k +=parseFloat($(this).val()|0);
})
$('input:text').val(k)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input type="number" class="value1" id="value1" path="commandName.object.field1" />
</form>
<form>
<input type="number" class="value1" id="value1" path="commandName.object.field2" />
</form>
<input type="text" disabled="disabled" id="result" />

Type on textfield when it has focus using button Javascript

I have one button that displays number "1" when clicked and three text boxes. I want when the button is clicked the number is displayed on the text box that has focus. Can someone help me please.
function run(){
document.calc.txt1.value += "1";
}
<input type=button name="btn1" value="1" OnClick="run()"id="button"><br />
<form name="calc">
<input type="text" id="txt1" name="txt1">
<input type="text" id="txt2" name="txt2">
<input type="text" id="txt3" name="txt3">
</form>
t3">
When you click a button, the previous input looses focus. You could try to store the last focused input element before the click:
(this needs some more work)
var lastFocus = null;
document.addEventListener("blur", function(event) {
// Here, you'll need to find out if the blurred element
// was one of your valid inputs. It's probably best to
// identify them by a class name
if (event.target.type === "text") {
lastFocus = event.target;
}
}, true);
function run() {
// When the user hasn't yet focused on a text input,
// the first one is used by default
(lastFocus || document.calc.txt1).value += "1";
}
<input type=button name="btn1" value="1" OnClick="run()"id="button"><br />
<form name="calc">
<input type="text" id="txt1" name="txt1">
<input type="text" id="txt2" name="txt2">
<input type="text" id="txt3" name="txt3">
</form>
var currId;
function setId(curr){
currId=curr.id;
}
function run(){
if(currId)
{
document.getElementById(currId).value +='1';
}
//document.calc.txt1.value += "1";
//document.activeElement.value += "1";
}
<input type=button name="btn1" value="1" OnClick="run()"id="button"><br />
<form name="calc">
<input type="text" id="txt1" name="txt1" onblur="setId(this)">
<input type="text" id="txt2" name="txt2" onblur="setId(this)">
<input type="text" id="txt3" name="txt3" onblur="setId(this)">
</form>
Ok, so this code snippet should do what you want. The main thing to note though is that whenever you click the button, the input box becomes blurred that you had selected.
Essentially what this code does here is set the onfocus attribute to allow you to figure out which input box was last focused, rather than which input box IS focused, because none are. Also, I'd recommend changing the button to a 'button' tag because it separates it in terms of tag name from the other input boxes.
Hope this helped, and let me know if you have any questions.
var inputs = document.getElementsByTagName('input');
for(var i = 1 ; i < inputs.length; i ++){
inputs[i].onfocus = function(){
this.setAttribute('class','focused');
}
}
function run(){
var inputBox = document.getElementsByClassName('focused')[0];
if(inputBox){
inputBox.value += "1";
inputBox.setAttribute('class','blurred');
}
}
<input type=button name="btn1" value="1" OnClick="run()"id="button"><br />
<form name="calc">
<input type="text" id="txt1" name="txt1">
<input type="text" id="txt2" name="txt2">
<input type="text" id="txt3" name="txt3">
</form>

Categories

Resources