How to show multiple input fields using onchange function? - javascript

$(document).on("change","#noofpack",function(){
count = $(this).val();
for(i=1;i<=count;i++){
$("#packageDiv").html('<input type="text" class="form-control" name="unit_price[]" placeholder="Unit Price" required="">');
}
});
I want to show multiple input fields onchange noofpack if count is 3 then it must show three input fields but what happen here when I change noofpack then it show only 1 input fields. So, How can I do this? Please help me.
Thank You

$(document).on("change","#noofpack",function(){
count = $(this).val();
$("#packageDiv").html(""); // First empty the packageDiv
for(i=1;i<=count;i++){
// Append more instead oh HTML
$("#packageDiv").append('<input type="text" class="form-control" name="unit_price[]" placeholder="Unit Price" required="">');
}
});

Related

jQuery data attribute updates only after second click

I have this jquery code which should print all selected checkboxes:
$('.engagement-type').on('click', function () {
var engagementTypes = $('.engagement-type').parent().find('[data-checkbox="checked"]');
console.log(engagementTypes);
});
12 checkboxes are in the table:
<td>
<input name="EngagementTypes[0].EngagementTypeId"
id="EngagementTypes_0__EngagementTypeId"
type="hidden" value="1" data-val-required="The Engagement field is required."
data-val="true" data-val-number="The field Engagement must be a number.">
<span class="pull-left">
<div class="engagement-type" data-checkbox="checked">
<input name="EngagementTypes[0].IsSelected"
id="EngagementTypes_0__IsSelected" type="checkbox" value="true"
data-val-required="The IsSelected field is required."
data-val="true">
<input name="EngagementTypes[0].IsSelected" type="hidden" value="false">
</div>
</span>
Audit
</td>
After first click on the checkbox I get empty list of selected engagement types. The first checkbox appears only after the second checkbox is checked. Why is that?
var engagementTypes = $('.engagement-type').parent().find('[data-checkbox="checked"]')
This will only work if you click on the div engagement-type. But if you click on one of the checkboxes in the div the parent is the one with the checkbox attribute, so he will not find another within this.
So you should always select
var elementYouWant = $('.engagement-type')
Then check if the data attribute is checked.
var dataElement = elementYouWant.data();
if (dataElement['checkbox'] == "checked") {
console.log("Oh yeah baby")
}
Ofcourse if there are multiple, you should do this in a loop for each of them.
As #T.J. Crowder mentioned, there must be additional code which you do not have provided.
At least the part which will set the data-checkbox = checked.
I would assume to use the checkbox state itself like:
$('.engagement-type').on('click', function () {
var engagementTypesChecked = $('.engagement-type').parent().find('input[type="checkbox"]:checked');
console.log(engagementTypesChecked);
});

OnInvalid html event triggering after Required modifier removed through JS

I have three input fields I am attempting to enforce validity on. Currently, I have them all set as required, but removing the modifier with Javascript on submit if one of them is filled out; essentially, one must fill out at least one, but not none of these fields.
Here is an example of the fields:
jQuery(function ($) {
var $inputs = $('input[name=Input1],input[name=Input2], input[name=Input3]');
$inputs.on('input', function () {
// Set the required property of the other input to false if this input is not empty.
$inputs.not(this).prop('required', $(this).val().length > 0 && $(this).val() != 0)
});
});
jQuery(function ($) {
$("#Input1, #Input2").oninvalid = (function() {
$(this).setCustomValidity("Please enter a valid Input1, Input2, or Input3")
});
});
var Input3default = document.getElementById('Input3')
if (Input3.value.length == 0) Input3.value = "0";
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<div class="input-group mb-3">
<form action="" method="get" autocomplete="off">
<div class="row" style="text-align:justify; width: 100%; display:inline">
<div class="">
<label for="text3">Input1:</label>
<input type="text" id="Input1" name="Input1" required oninvalid="this.setCustomValidity('Please enter a valid Input1, Input2, or Input3')" />
</div>
<div class="">
<label for="text4">Input2:</label>
<input type="text" id="Input2" name="Input2" required oninvalid="this.setCustomValidity('Please enter a valid Input1, Input2, or Input3')"/>
</div>
<div class="">
<label for="text5">Input3:</label>
<input type="text" id="Input3" name="Input3" required placeholder="0" pattern="[0-9]*" onsubmit="Input3default" oninvalid="this.setCustomValidity('Please enter a valid Input3')"/>
</div>
</div>
<p>
<input type="submit" value=" Submit " />
</p>
</form>
</div>
</div>
This seems to work fine if I leave it default; I have Input1 and Input2 empty by default, and Input3 has a value of "0" by default. If I enter Input1 or Input2, my submission goes through just fine. However, the problems begin if I alter Input3.
Problem 1: Any time I enter Inputs 1 and 2 but leave 3 blank, it triggers invalidity; my Input3default never seems to trigger, and it is passed blank and caught by the oninvalid tag.
Problem 2: Along with that, if I do not specify an Input2 along with my Input1 while Input3 is blank, it triggers invalidity on Input2. Using Chrome Debugger, I can see that the Required tag is removed, but my OnInvalid pop-up still comes up no matter what is remedied.
Essentially, I am trying to solve the second problem: When I remove the required html tag from my input, after invalidating another input with a Javascript-enforced default, my inputs refuse to validate on the front end.
I appreciate any advice and conjecture as to why this may be the case, and believe that the two problems are connected.
EDIT: Upon adding an = to my original oninvalid JQuery function, I removed a JS error. It appears that my Input3 default function triggers on pageload, but not on submit; I added an onsubmit function to input3, but am still receiving oninvalid events for input2.
I was able to fix this issue on my own, using the OnInput event.
The setCustomValidity function, when triggered, does not allow a submission while a CustomValidity is set. In order to fix this, I edited my inputs as so:
<input type="text" id="Input1" name="Input1" required oninvalid="this.setCustomValidity('Please enter a valid Input1, Input2, or Input3')" oninput="this.setCustomValidity('')"/>
I still have a few kinks to iron out, but this fixed my main problem in that the validity of an input was not being reset.
I'll leave this answer unaccepted at first to allow others to pitch in.

Why appended input field submit not working?

When user enter the key press I used Jquery to submit form and after I append another <input> field for another input. But the problem is appended input field submit not working... Instead it expecting the old one.
Code
// html
<div class="ten columns">
<input id="txt_name" class="u-full-width" name="a" type="text" autofocus>
</div>
// javascript
$('#txt_name').keypress(function (e) {
if (e.which == 13) {
$.getJSON('/_main_submit', {
a: $('input[name="a"]').val(),
}, function(data){
$('.after_sub').append(
'<div class="ten columns">'+
'<input id="txt_name" class="u-full-width" name="a" type="text" autofocus>'+
'</div>'
)
$('div input').focus();
})
return false;
}
});
You can only have one element with a certain id in the DOM. Use classes instead of id's for your input fields. Your new input also has the same name, that should be changed, too, if you expect the form to have more than one input field.

How to prevent inputting 0 in an specific input through jquery and show an error div through jquery?

I am trying to prevent inputting a value as 0 in an specific input field and show an error div on inputting 0 in the input so please it will be kindful if you pleaes guide me..!
I would like to use jquery please..!
code for the following field as :
<input name="invoice_price" class="form-control">
HTML :-
<input name="invoice_price" class="form-control">
<div id="div1" style="color:red"></div>
Jquery :-
$(document).ready(function(){
$("input[name='invoice_price']").on('blur keyup',function(){
if($(this).val()=='0')
{
$("#div1").html('0 value not allowed');
$(this).val('');
}
else
{
$("#div1").html('');
}
});
});
Fiddle link :- http://jsfiddle.net/0mat1amf/1/
As questioner asked another question in comments section(that user can only enter maximum three digits) then i m adding more code here :
<input name="invoice_price" class="form-control" type="text" maxlength="3">
This is what you could use if you want to stack up error messages:
$(document).ready(function(){
$("input[name=invoice_price]").change(function(){
if ($(this).val()==0)
$(this).after("<div>Error message</div>");
});
});
It will create error message right after the input element every time the input is changed and is wrong. Instead you might want to have predefined div and only change its contents like:
<input name="invoice_price" class="form-control">
<div></div>
$(document).ready(function(){
$("input[name=invoice_price]").change(function(){
if ($(this).val()==0)
$(this).next().html("Error message");
});
});
HTML:
<input name="invoice_price" class="form-control"
onblur="(this.value == 0) ? (this.value = '') : ''" />
Demo
This will ensure that user cannot enter zero value. No need of showing an error!

How can I show input fields only when previous input has a valid value?

I have a form that requires between 3 and 10 text input items. When the form first loads it will show 3 inputs (minimum).
I'd like to efficiently show input rows as the previous row has a valid value (let's assume greater than 3 characters for example). So if you fill out the first 3, you will automatically see a 4th optional input row.
Can you help me loop through this quick list efficiently in jQuery?
HTML:
<input type="text" class="item_1" name="item_1">
<input type="text" class="item_2" name="item_2">
<input type="text" class="item_3" name="item_3">
<input type="text" class="item_4" name="item_4">
<input type="text" class="item_5" name="item_5">
<input type="text" class="item_6" name="item_6">
<input type="text" class="item_7" name="item_7">
<input type="text" class="item_8" name="item_8">
<input type="text" class="item_9" name="item_9">
<input type="text" class="item_10" name="item_10">
CSS:
.item_4,.item_5,.item_6,.item_7,.item_8,.item_9,.item_10 { display:none }
This is pretty simple - you shouldn't even need a loop if you let jQuery's chaining do the work. I'd do something like:
$("#myform input").change(function(){ //If an input in your form is changed,
if ($(this).val() == 42){ //replace with your validation logic :)
$(this).next('input').show(); //This shows the next sibling element to the triggering element
} else { //but if it fails validation...
$(this).nextAll('input').hide().val(""); //hide them and delete the contents to stop the form from uploading invalidated data!
}
});
This does what you asked, and for bonus points it hides and empties later boxes if their predecessors are later changed to be invalid.

Categories

Resources