http://jsfiddle.net/R89fn/9/
If any of the text input/Box added are empty then the page must not submit.when I try to retrieve values from the text inputs using their id`s nothing gets retrieved is it possible to retrieve values from elements added dynamically?
$("#submit").click(function (event) {
var string = "tb";
var i;
for (i = 1; i <= count; i++) {
if (document.getElementById(string+1).value=="") {
event.preventDefault();
break;
}
}
});
The above code is what I am using to get the value from the text fields using there id
I took a look on the code in the JSFiddle. It appears that the input textboxes are not given the intended IDs; the IDs are given to the container div.
The code for the add button should use this,
var inputBox = $('<input type="text" id="td1">') //add also the needed attributes
$(containerDiv).append(inputBox);
Check out this solution on fiddle: http://jsfiddle.net/R89fn/15/
var count = 0;
$(document).ready(function () {
$("#b1").click(function () {
if (count == 5) {
alert("Maximum Number of Input Boxes Added");
} else {
++count;
var tb = "tb" + count;
$('#form').append("<div class=\"newTextBox\" id=" + tb + ">" + 'InputField : <input type="text" name="box[]"></div>');
}
});
$("#b2").click(function () {
if (count == 0) {
alert("No More TextBoxes to Remove");
} else {
$("#tb" + count).remove();
--count;
}
});
$("#submit").click(function (event) {
var inputBoxes = $('#form').find('input[type="text"]');;
if (inputBoxes.length < 1) {
alert('No text inputs to submit');
return false;
} else {
inputBoxes.each(function(i, v) {
if ($(this).val() == "") {
alert('Input number ' + (i + 1) + ' is empty');
$(this).css('border-color', 'red');
}
});
alert('continue here');
return false;
}
});
});
<form name="form" id="form" action="htmlpage.html" method="POST">
<input type="button" id="b1" name="b1" value="Add TextBox" />
<input type="button" id="b2" name="b2" value="Remove TextBox" />
<input type="submit" id="submit" name="submit" value="Submit" />
</form>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<script>
var count = 0;
$(document).ready(function() {
$("#b1").click(function() {
if (count == 5) {
alert("Maximum Number of Input Boxes Added");
} else {
++count;
var tb = "tb" + count;
$(this).before("<div class=\"newTextBox\" id= "+ tb +" >" + 'InputField : <input type="text" name="box[]"></div>');
}
});
$("#b2").click(function() {
if (count == 0) {
alert("No More TextBoxes to Remove");
} else {
$("#tb" + count).remove();
--count;
}
});
$("#submit").click(function(event) {
var string = "#texttb";
var i;
for (i = 1; i <= count; i++) {
if ($('input[type = text]').val() == "") {
event.preventDefault();
break;
}
}
});
});
</script>
<style>
.newTextBox
{
margin: 5px;z
}
</style>
Reason:
you had given id to the div element. so its not get retrive. i had updated the answer with the usage of jquery functions and changed your code for this requirement.
If I understand correctly, your only issue atm is to make sure that the form is not sent if one of the inputs are empty? Seems the solution to your problem is simpler. Simply add required at the end of any input and HTML5 will ensure that the form is not sent if empty. For example:
<input type="text" required />
Related
I am trying to create a search form using jquery for following tasks to do:
A user can upload file or input text into the text area or select option from the drop-down menu but these options will appear based on the selection of 1st drop-down menu.
The user can clone this form number of times but not more than max options of the 1st drop-down menu.
The user can remove form < max options from the 1st drop-down menu.
But problems are:
Task 1 is working only on the original form but not in cloned one.I think due to the tag id, it only does the task for original one, so how can I do that for multiple occasion?
var max_fields = 3; //maximum input boxes allowed
var wrapper = $(".input_fields_wrap"); //Fields wrapper
var addButton = $("#form-add"); //Add button ID
var form = $('#main-form');
var x = 1; //initlal text box count
$('#alarm_action').change(function (e) {
if ($("#alarm_action").val() == "listofcompany") {
$('#filefield').show();
$("#myTextarea").hide();
$("#showForProg").hide();
} else if ($("#alarm_action").val() == "runprogram") {
$('#filefield').hide();
$("#myTextarea").hide();
$("#showForProg").show();
} else {
$('#filefield').hide();
$("#myTextarea").show();
$("#showForProg").hide();
}
});
$(addButton).click(function(e){ //on add input button click
e.preventDefault();
if(x < max_fields){ //max input box allowed
x++; //text box increment
$(wrapper).append('<div class="form-field">\
<select class="removeDuplication" name="searchtype" id="alarm_action" required>\
<option value="cityname">City Name</option>\
<option value="listofcompany">Company</option>\
<option value="runprogram">Run Program</option></select>\
<body onload="setProg();">\
<select name="searchtermorg" id="showForProg" style="display: none;"></select>\
</body>\
<input id="filefield" type="file" name="foofile" style="display: none;"/>\
<textarea id="myTextarea" name="something" ></textarea>\
Remove\
</div>'); //add input box
} else {
alert("Sorry, you have reached maximum add options.");
}
});
$(wrapper).on("click",".remove_field", function(e){ //user click on remove text
e.preventDefault();
$(this).parent('div').remove();
x--;
});
$(document).on('change','select.removeDuplication',function(e) {
e.preventDefault();
var cI = $(this);
var others=$('select.removeDuplication').not(cI);
$.each(others,function(){
if($(cI).val()==$(this).val() && $(cI).val()!="") {
$(cI).val('');
alert($(this).find('option:selected').text()+' already selected.');
}
});
});
form.on('submit', function(e) {
e.preventDefault()
var queries = [];
var slectedall=true;
var fillupfield=true;
form.find('.form-field').each(function(index, field) {
var query = {};
query.type = $(field).find('select').val();
console.log(query.type);
if (query.type !=""){
if (query.type == "listofcompany") {
query.value =$(field).find('#filefield').val();
} else if (query.type == "runprogram") {
query.value =$(field).find('#showForProg').val();
} else {
query.value =$(field).find('textarea').val().replace(/\n/g, '\\n');
}
queries.push(query);
} else{
slectedall=false;
}
});
var url = window.location.href;
url+="/search/advanced/";
for (i = 0; i < queries.length; i += 1) {
var query = queries[i];
var ampOrQ = (i === 0) ? "?" : "&";
if (query.value.trim() ===""){
fillupfield=false;
} else {
url += ampOrQ + query.type + "=" + query.value;
}
};
if (slectedall===false){
alert('Please select option.');
} else {
if (fillupfield===false){
alert('Input can not be left blank');
} else {
//alert(url);
window.location.href = url;
}
}
});
var progarray = ['Python','Java','R'];
function setProg() {
var newOptions=progarray;
var newValues=progarray;
selectField = document.getElementById("showForProg");
selectField.options.length = 0;
for (i=0; i<newOptions.length; i++)
{
selectField.options[selectField.length] = new Option(newOptions[i], newValues[i]);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form id="main-form" class="navbar-form" action="" method="get" enctype='multipart/form-data'>
<div class="input_fields_wrap">
<div class="form-field">
<select class="removeDuplication" name='searchtype' id="alarm_action" required>
<option value="cityname">City Name</option>
<option value="listofcompany">Company</option>
<option value="runprogram">Run Program</option></select>
<body onload="setProg();">
<select name="searchtermorg" id="showForProg" style="display: none;"></select>
</body>
<input id="filefield" type="file" name="foofile" style="display: none;"/>
<textarea id="myTextarea" name="something"></textarea>
</div>
</div>
<input class="btn btn-secondary" type="button" value="Add" id="form-add">
<input class="btn btn-primary" type="submit" value="Submit">
</form>
Can anybody help me to fix these problems? thank you
Issues with our current code:
In a valid HTML, idof an element should be unique. But here you are repeating the element id every time you clone the elements. Use class instead of id.
Use $.on to bind events to elements which are added dynamically (eg, the dropdown change event)
Spaghetti code which is not maintainable - I've tried cleaning up a bit. But there is a lot of scope for clean up.
I've fixed the issue which you have mentioned by fixing the above-mentioned points. But as I said, there is a lot of clean-up to be done before this could be used in a project.
var max_fields = 3; //maximum input boxes allowed
var wrapper = $(".input_fields_wrap"); //Fields wrapper
var addButton = $("#form-add"); //Add button ID
var form = $('#main-form');
var x = 1; //initlal text box count
var progarray = ['Python', 'Java', 'R'];
wrapper.append($("#content-template").html());
//alert($(".showForProg").length);
setProg($(".showForProg"));
$(document).on('change', '.alarm_action', function(e) {
var $container = $(this).parents('.form-field');
if ($(this).val() == "listofcompany") {
$('.filefield', $container).show();
$(".myTextarea", $container).hide();
$(".showForProg", $container).hide();
} else if ($(this).val() == "runprogram") {
$('.filefield', $container).hide();
$(".myTextarea", $container).hide();
$(".showForProg", $container).show();
} else {
$('.filefield', $container).hide();
$(".myTextarea", $container).show();
$(".showForProg", $container).hide();
}
});
$(addButton).click(function(e) { //on add input button click
e.preventDefault();
if (x < max_fields) { //max input box allowed
x++; //text box increment
wrapper.append($("#content-template").html());
setProg($(".showForProg").last());
} else {
alert("Sorry, you have reached maximum add options.");
}
});
$(wrapper).on("click", ".remove_field", function(e) { //user click on remove text
e.preventDefault();
$(this).parent('div').remove();
x--;
});
$(document).on('change', 'select.removeDuplication', function(e) {
e.preventDefault();
var cI = $(this);
var others = $('select.removeDuplication').not(cI);
$.each(others, function() {
if ($(cI).val() == $(this).val() && $(cI).val() != "") {
$(cI).val('');
alert($(this).find('option:selected').text() + ' already selected.');
}
});
});
form.on('submit', function(e) {
e.preventDefault()
var queries = [];
var slectedall = true;
var fillupfield = true;
form.find('.form-field').each(function(index, field) {
var query = {};
query.type = $(field).find('select').val();
console.log(query.type);
if (query.type != "") {
if (query.type == "listofcompany") {
query.value = $(field).find(',filefield').val();
} else if (query.type == "runprogram") {
query.value = $(field).find(',showForProg').val();
} else {
query.value = $(field).find('textarea').val().replace(/\n/g, '\\n');
}
queries.push(query);
} else {
slectedall = false;
}
});
var url = window.location.href;
url += "/search/advanced/";
for (i = 0; i < queries.length; i += 1) {
var query = queries[i];
var ampOrQ = (i === 0) ? "?" : "&";
if (query.value.trim() === "") {
fillupfield = false;
} else {
url += ampOrQ + query.type + "=" + query.value;
}
};
if (slectedall === false) {
alert('Please select option.');
} else {
if (fillupfield === false) {
alert('Input can not be left blank');
} else {
//alert(url);
window.location.href = url;
}
}
});
function setProg($programDropdown) {
$.each(progarray , function(key, value) {
$programDropdown
.append($("<option></option>")
.attr("value",value)
.text(value));
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form id="main-form" class="navbar-form" action="" method="get" enctype='multipart/form-data'>
<div class="input_fields_wrap">
</div>
<input class="btn btn-secondary" type="button" value="Add" id="form-add">
<input class="btn btn-primary" type="submit" value="Submit">
</form>
<script type="text/template" id="content-template">
<div class="repeat-container">
<div class="form-field">
<select class="alarm_action removeDuplication" name='searchtype' required>
<option value="cityname">City Name</option>
<option value="listofcompany">Company</option>
<option value="runprogram">Run Program</option></select>
<body>
<select name="searchtermorg" class="showForProg" style="display: none;"></select>
</body>
<input class="filefield" type="file" name="foofile" style="display: none;" />
<textarea class="myTextarea" name="something"></textarea>
</div>
</div>
</script>
I have this code to validate 2 input text, but how can I validate same input for
dynamic intput text ? meaning input text quantity can be up to 100 or more.
<input type="text" id="id1" />
<input type="text" id="id2" />
$('input').blur(function() {
if ($('#id1').attr('value') == $('#id2').attr('value')) {
alert('Same Value');
return false;
} else { return true; }
});
If you want to check all the inputs are the same (I gather that's what you're trying to do) you could just loop through them by using a function like this:
function validate() {
for (var i = 2; i <= 100; i++) {
if ($('#id' + x).val() !== $('#id' + (x - 1)).val()) {
return false;
}
}
return true;
}
Of course, you may want to create inputs themselves using a loop too if you'll have that many on the page.
<input type="text" id="id1" onblur="validate()">
<input type="text" id="id2" onblur="validate()">
<p style="display: none">Test</p>
<script type="text/javascript">
function validate() {
for (var i = 1; i <= 2; i++) {
if ($('#id' + i).val() == $('#id' + (i - 1)).val()) {
$( "p" ).show( "slow" ); return false;
}
else
{
$( "p" ).hide( 1000 );
}
}
return true;
}
</script>
What I did is this hope someone can you this in future reference
Below is my working code but the only problem is, I want the check box to checked by default and show the jquery output on page load but it only show output when i re-check the check box.
http://jsfiddle.net/pratyush141/2mq5sr1h/
$(function() {
$defaultValue = $('.total').val();
$("input[type=checkbox]").click(function(event) {
var total = 0;
$("input:checked").each(function() {
total += parseInt($(this).parent().find('.inv-total').text().substring(1));
});
if (total == 0) {
$('.total').val($defaultValue);
} else {
$('.total').val('$' + total);
}
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<div class="invoice">
<input type="checkbox" checked='checked' value="1" />
<span class="inv-total">$100</span>
</div>
<input type="text" class="total" value="$90" />
It's simple, just remove the checked=checked from the checkbox, then use jquery to call the click on checkbox
<div class="invoice">
<input type="checkbox" value="1" />
<span class="inv-total">$100</span>
</div>
$(function () {
$defaultValue = $('.total').val();
$("input[type=checkbox]").change(function (event) {
var total = 0;
$("input:checked").each(function () {
total += parseInt($(this).parent().find('.inv-total').text().substring(1));
});
if (total == 0) {
$('.total').val($defaultValue);
} else {
$('.total').val('$' + total);
}
});
//Call the click on checkbox
$("input[type=checkbox]").click();
})
Working fiddle: http://jsfiddle.net/2mq5sr1h/5/
You set value of input on click event. You need to set it in $(document).ready(). Try to change your script to this:
$(document).ready(function (){
setValue();
$("input[type=checkbox]").click(function(event) {
setValue();
});
});
function setValue()
{
$defaultValue = $('.total').val();
var total = 0;
$("input:checked").each(function() {
total += parseInt($(this).parent().find('.inv-total').text().substring(1));
});
if (total == 0) {
$('.total').val($defaultValue);
}
else {
$('.total').val('$' + total);
}
}
Ok i have multy fields with same name, and i want to check is all fields are not empty. My code works if i have only one input, but i have no idea how to do that with more inputs
<input class = "new_input" type=text name="name[]"/>
<input class = "new_input" type=text name="name[]"/>
function validation(){
var x = document.forms["form"]["name"].value;
if(x ==='')
{
$("#warning").html("Morate uneti vrednost!").css('color','red');
return false;
}
else
{
return true;
}
}
for example if enter only one field, validation will work, and i want to check all fields
Using just JS you could do something like
<input class="new_input" type="text" name="name[]">
<input class="new_input" type="text" name="name[]">
<input class="new_input" type="text" name="name[]">
<input class="new_input" type="text" name="name[]">
<button onclick="validate()">Validate</button>
<script type="text/javascript">
function validate() {
var inputs = document.getElementsByTagName("input");
var empty_inputs = 0;
for(var i = 0; i < inputs.length; i++) {
if(inputs[i].name.indexOf('name') == 0) { // check all inputs with 'name' in their name
if (inputs[i].value == '') {
empty_inputs++;
console.log('Input ' + i + ' is empty!');
}
}
}
if (empty_inputs == 0) {
console.log('All inputs have a value');
}
}
</script>
You have tagged jquery, so I have given something which works in jquery
http://jsfiddle.net/8uwo6fjz/1/
$("#validate").click(function(){
var x = $("input[name='name[]']")
$(x).each(function(key,val){
if($(val).val().length<=0)
{
$("#warning").html("Morate uneti vrednost!").css('color','red');
}
});
});
Try this:
function validate(){
var error = 0;
$.each( $("input[name='name[]']"), function(index,value){
if( value.value.length == 0){
$("#warning").html("Morate uneti vrednost!").css('color','red');
error = 1;
return;
}
});
if(!error){
$("#warning").html("");
}
}
Check it out here: jsFiddle
I am available with the solution given by #Tomalak for MY QUESTION could you pls help me out with it as its giving me an error in firebug as : frm.creatorusers is undefined
[Break On This Error] var rdo = (frm.creatorusers.length >...rm.creatorusers : frm.creatorusers;
I used the code for validating radio button as:
function valDistribution(frm) {
var mycreator = -1;
var rdo = (frm.creatorusers.length > 0) ? frm.creatorusers : frm.creatorusers;
for (var i=0; i<rdo.length; i++) {
if (rdo[i].checked) {
mycreator = 1;
//return true;
}
}
if(mycreator == -1){
alert("You must select a Creator User!");
return false;
}
}
Here is how to use the code you were given by #Tomalak but did not copy correctly
function valDistribution(frm) { // frm needs to be passed here
var myCreator=false;
// create an array if not already an array
var rdo = (frm.creatorusers.length > 0) ? frm.creatorusers : [frm.creatorusers];
for (var i=0; i<rdo.length; i++) {
if (rdo[i].checked) {
myCreator=true;
break; // no need to stay here
}
if (!myCreator){
alert("You must select a Creator User!");
return false;
}
return true; // allow submission
}
assuming the onsubmit looking EXACTLY like this:
<form onsubmit="return valDistribution(this)">
and the radio NAMED like this:
<input type="radio" name="creatorusers" ...>
You can try this script:
<html>
<script language="javascript">
function valbutton(thisform) {
myOption = -1;
alert(thisform.creatorusers.length);
if(thisform.creatorusers.length ==undefined) {
alert("not an array");
//thisform.creatorusers.checked = true;
if(thisform.creatorusers.checked) {
alert("now checked");
myOption=1;
alert("You selected button number " + myOption
+ " which has a value of "
+ thisform.creatorusers.value);
}
}
else {
for (i=thisform.creatorusers.length-1; i > -1; i--) {
if (thisform.creatorusers[i].checked) {
myOption = i; i = -1;
}
}
if (myOption == -1) {
alert("You must select a radio button");
return false;
}
alert("You selected button number " + myOption
+ " which has a value of "
+ thisform.creatorusers[myOption].value);
}
}
</script>
<body>
<form name="myform">
<input type="radio" value="1st value" name="creatorusers" />1st<br />
<!--<input type="radio" value="2nd value" name="creatorusers" />2nd<br />-->
<input type="button" name="submitit" onclick="valbutton(myform);return false;" value="Validate" />
<input type="reset" name="reset" value="Clear" />
</form>
</body>
</html>