Required field form by using id attribute in Javascript - javascript

here is my form. When user want to add another form they just click the "tambah bil".
my problem is the function of required just detect the name of input filed. I want the function of required detect by the id of input field because it have the same name in one form.
<fieldset>
<div id="item">
<div class="callout callout-warning" style="margin-top:15px">
<div class="row">
<div class="col-md-12">
<h6><i class="far fa-file-alt"style="font-size:20px"></i><b style="padding-left:7px">Maklumat Bil</b>
<span class="float-sm-right">
<button type="button" name="add" id="add" class="btn btn-block btn-primary btn-sm right add"><i class="fa fa-plus"></i> Tambah Bil</button>
</span></h6><hr>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label>Jabatan</label>
<input type="hidden" name="jabatan[]" class="form-control" value="<?php echo $dept; ?>">
<span class="form-control form-control-sm"><?php echo $jab; ?></span>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label>Kod*</label>
<select class="form-control select2bs4" name="kod[]" id= "kod" required>
<option value="" disabled="disabled" selected="selected">--Pilih Kod--</option>?php foreach($kod as $k):?>
<option value="<?php echo $k->kod;?>"><?php echo $k->kod;?> - <?php echo $k->keterangan;?></option>
<?php endforeach;?>
</select>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label>Perkara (Wajid isi ruangan pertama)*</label>
<input type="text" class="form-control form-control-sm" name="perkara1[]" id="perkara1" required>
<input type="text" class="form-control form-control-sm" name="perkara2[]" id="perkara2" required="false" style="margin-top:6px !important" >
<input type="text" class="form-control form-control-sm" name="perkara3[]" id="perkara3" required="false" style="margin-top:6px !important" >
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label>No. Rujukan*</label>
<input id="noruj" type="text" class="form-control form-control-sm" name="noruj[]" required>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label>Jumlah (RM)* </label>
<input type="text" id="currency" class="form-control form-control-sm currency" name="jumlah[]" required>
</div>
</div>
</div>
<span>*Ruangan wajib diisi</span>
</div>
</div>
</fieldset>
here is my form in javascript when user want to add another bil.
$('html, body').animate({scrollTop: '+=550px'}, 400);
var html = '';
html += '<div class="callout callout-warning">';
html += '<div class="row"><div class="col-md-12"><h6><i class="far fa-file-alt"style="font-size:20px"></i><b style="padding-left:7px">Maklumat Bil</b><span class="float-sm-right" style="padding-left:5px"><button type="button" name="remove" class="btn btn-block btn-danger btn-sm right remove"><i class="fa fa-minus"></i> Padam Bil</button></span><span class="float-sm-right"><button type="button" name="add" class="btn btn-block btn-primary btn-sm right add"><i class="fa fa-plus"></i> Tambah Bil</button></span></h6><hr></div></div>';
html += '<div class="row"><div class="col-md-12"><div class="form-group"><label>Jabatan*</label><input type="hidden" name="jabatan[]" class="form-control" value="<?php echo $dept; ?>"><span class="form-control form-control-sm"><?php echo $jab; ?></span></div></div></div>';
html += '<div class="row"><div class="col-md-6">';
//html += '<div class="form-group"><label>Kategori*</label><select name="kategori'+i+'[]" class="form-control select2bs4" style="width: 100%;" required><option value="" disabled="disabled" selected="selected">--Pilih Kategori--</option><option value="INDIVIDU">Individu</option><option value="SYARIKAT">Syarikat</option></select></div>';
html += '<div class="form-group"><label>Kod*</label><select class="form-control select2bs4" name="kod[]" id ="kod'+i+'" required><option value="" disabled="disabled" selected="selected">--Pilih Kod--</option><?php foreach($kod as $k):?><option value="<?php echo $k->kod;?>"><?php echo $k->kod;?> - <?php echo $k->keterangan;?></option><?php endforeach;?></select></div>';
html += '</div><div class="col-md-6">';
html += '<div class="form-group"><label>Perkara (Wajib isi ruangan pertama)*</label><input type="text" class="form-control form-control-sm" name="perkara1[]" id="perkara1'+i+'" required><input type="text" class="form-control form-control-sm" name="perkara2[]" id="perkara2'+i+'" style="margin-top:6px !important" ><input type="text" class="form-control form-control-sm" name="perkara3[]" id="perkara3'+i+'" style="margin-top:6px !important" ></div>';
html += '</div></div>';
html += '<div class="row"><div class="col-md-6">';
html += '<div class="form-group"><label>No. Rujukan*</label><input id="noruj'+i+'" type="text" class="form-control form-control-sm" name="noruj[]" required></div>';
html += '</div><div class="col-md-6">';
html += '<div class="form-group"><label>Jumlah (RM)*</label><input type="text" id="currency" class="form-control form-control-sm currency" name="jumlah[]" required></div>';
html += '</div><span>*Ruangan wajib diisi</span></div>';
html += '</div>';
$('#item').append(html);
$(function()
{
const inputs = $("input").prop('required',true);
console.log('return value:');
inputs.each(log);
console.log('');
console.log('selector:');
$("input[required]").each(log);
function log(index, element)
{
console.log($(element).attr("id"));
}
});
the coding required field just read input field outside the javascript...
how i want to detect the input in javascript form is required by using id attribute??
function required cannot detect the id of input field, function detect the name of input field it is because in one form have same name of input field.
anybody can help me??
thank you in advance.

You could use it immediately after you set the prop
const inputs = $("input").prop('required',true);
console.log(inputs);
You can also use an attribute selector
const inputs = $("input[required]");
const i = 1;
$('html, body').animate({scrollTop: '+=550px'}, 400);
var html = '';
html += '<div class="callout callout-warning">';
html += '<div class="row"><div class="col-md-12"><h6><i class="far fa-file-alt"style="font-size:20px"></i><b style="padding-left:7px">Maklumat Bil</b><span class="float-sm-right" style="padding-left:5px"><button type="button" name="remove" class="btn btn-block btn-danger btn-sm right remove"><i class="fa fa-minus"></i> Padam Bil</button></span><span class="float-sm-right"><button type="button" name="add" class="btn btn-block btn-primary btn-sm right add"><i class="fa fa-plus"></i> Tambah Bil</button></span></h6><hr></div></div>';
html += '<div class="row"><div class="col-md-12"><div class="form-group"><label>Jabatan*</label><input type="hidden" name="jabatan[]" class="form-control" value="<?php echo $dept; ?>"><span class="form-control form-control-sm"><?php echo $jab; ?></span></div></div></div>';
html += '<div class="row"><div class="col-md-6">';
//html += '<div class="form-group"><label>Kategori*</label><select name="kategori'+i+'[]" class="form-control select2bs4" style="width: 100%;" required><option value="" disabled="disabled" selected="selected">--Pilih Kategori--</option><option value="INDIVIDU">Individu</option><option value="SYARIKAT">Syarikat</option></select></div>';
html += '<div class="form-group"><label>Kod*</label><select class="form-control select2bs4" name="kod[]" id ="kod'+i+'" required><option value="" disabled="disabled" selected="selected">--Pilih Kod--</option><?php foreach($kod as $k):?><option value="<?php echo $k->kod;?>"><?php echo $k->kod;?> - <?php echo $k->keterangan;?></option><?php endforeach;?></select></div>';
html += '</div><div class="col-md-6">';
html += '<div class="form-group"><label>Perkara (Wajib isi ruangan pertama)*</label><input type="text" class="form-control form-control-sm" name="perkara1[]" id="perkara1'+i+'" required><input type="text" class="form-control form-control-sm" name="perkara2[]" id="perkara2'+i+'" style="margin-top:6px !important" ><input type="text" class="form-control form-control-sm" name="perkara3[]" id="perkara3'+i+'" style="margin-top:6px !important" ></div>';
html += '</div></div>';
html += '<div class="row"><div class="col-md-6">';
html += '<div class="form-group"><label>No. Rujukan*</label><input id="noruj'+i+'" type="text" class="form-control form-control-sm" name="noruj[]" required></div>';
html += '</div><div class="col-md-6">';
html += '<div class="form-group"><label>Jumlah (RM)*</label><input type="text" id="currency" class="form-control form-control-sm currency" name="jumlah[]" required></div>';
html += '</div><span>*Ruangan wajib diisi</span></div>';
html += '</div>';
$('#item').append(html);
$(function()
{
const inputs = $("input").prop('required',true);
console.log('return value:');
inputs.each(log);
console.log('');
console.log('selector:');
$("input[required]").each(log);
function log(index, element) {
console.log($(element).attr('name'));
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="item"></div>

Related

By click of the button the same form is added under that form but how can i get the value of the number of times it getting printed &store it in table

by click of the button the same form is added under that form but how can i get the value of the number of times it getting printed &store it in table. How can I insert the data into table if the user add more experiences from model. On the click of the button the value in the value field should increment too and how can I enter if the user add any number of experiences so how can I enter the data in the table. I am inserting this data in table in row wise fashion in table
<div class="col-md-12" id="addexperience">
<button type="button" class="btn-primary" style="float:right;" onclick="addexperience()">Add work experience</button>
<input type="hidden" name="1experience" id="1experience" value="<?php $i = 1; ?>">
<div class="form-group">
<label>If yes, fill the following table</label>
<div class="col-md-3">
<label>Status</label>
<select class="form-control" name="status">
<option value="">Select</option>
<option value="1" <?php sel($student_experience['status'], '1'); ?>>Current</option>
<option value="0" <?php sel($student_experience['status'], '0'); ?>>Past</option>
</select>
</div>
<div class="col-md-3">
<label>Designation</label>
<input type="text" class="form-control" name="designation" value="<?php echo esc_output($student_experience['designation']);?>">
</div>
<div class="col-md-3">
<label>Duration</label>
<input type="number" class="form-control" name="duration" value="<?php echo esc_output($student_experience['duration']);?>">
</div>
<div class="col-md-3">
<label>Employer</label>
<input type="text" class="form-control" name="employer" value="<?php echo esc_output($student_experience['employer']);?>">
</div>
</div>
</div>
<script>
function addexperience(){
var i = $('#1experience').val();
i++;
$('#addexperience').append('<div class="col-md-3"> <label>Status</label> <select class="form-control" name="status'+i+'">'+
'<option value="">Select</option>'+
'<option value="Current">Current</option>'+
'<option value="Past">Past</option> </select> </div>'+
'<div class="col-md-3">'+
'<label>Designation</label>'+
'<input type="text" class="form-control" name="designation'+i+'">'+
'</div>'+
'<div class="col-md-3">'+
'<label>Duration</label>'+
'<input type="text" class="form-control" name="duration'+i+'">'+
'</div>'+
'<div class="col-md-3">'+
'<label>Employer</label>'+
'<input type="text" class="form-control" name="employer'+i+'">'+
'</div>'+
'</div>');
$(function () {
$('#1experience').val(i);
});
}
</script>
If you modify the HTML slightly in both the initial page display and within the javascript function so that the newly added items are grouped within a single container(div) and the initial elements are similarly grouped and a name assigned to the immediate ancestor of the initially displayed elements ( here I chose data-id='receiver' ) then this matter of deducing the number of times the elements have been added becomes a matter of counting the child elements within the common parent - querySelectorAll being useful here though no doubt jQuery has a concise method to do this too.
With that said though if you were to use the array syntax form form element names, such as designation[] or duration[] when the form is submitted you will have access to each element as an array in PHP ( or other backend language ) which will also, as a byproduct, reveal that same number of elements. Using the array syntax means you do not need to try to keep track of this number within the client
function addexperience() {
let i=document.querySelectorAll('[data-id="receiver"] > div').length;
$('[data-id="receiver"]').append('<div><div class="col-md-3"> <label>Status</label> <select class="form-control" name="status' + i + '">' +
'<option value="">Select</option>' +
'<option value="Current">Current</option>' +
'<option value="Past">Past</option> </select> </div>' +
'<div class="col-md-3">' +
'<label>Designation</label>' +
'<input type="text" class="form-control" name="designation' + i + '">' +
'</div>' +
'<div class="col-md-3">' +
'<label>Duration</label>' +
'<input type="text" class="form-control" name="duration' + i + '">' +
'</div>' +
'<div class="col-md-3">' +
'<label>Employer</label>' +
'<input type="text" class="form-control" name="employer' + i + '">' +
'</div>' +
'</div></div>');
alert(i);
document.querySelector('input[name="duplicates"]').value=i;
fetch( location.href, {method:'post',body:'total='+i})
.then(r=>r.text())
.then(text=>{
alert(text)
})
}
[data-id='receiver']{border:1px solid red;margin:1rem;padding:1rem;}
[data-id='receiver'] > div{margin:1rem;border:1px solid black;padding:0.5rem}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col-md-12" id="addexperience">
<button type="button" class="btn-primary" style="float:right;" onclick="addexperience()">Add work experience</button>
<div data-id='receiver' class="form-group">
<div>
<label>If yes, fill the following table</label>
<div class="col-md-3">
<label>Status</label>
<select class="form-control" name="status">
<option value="">Select</option>
<option value="1" <?php sel($student_experience[ 'status'], '1'); ?>>Current</option>
<option value="0" <?php sel($student_experience[ 'status'], '0'); ?>>Past</option>
</select>
</div>
<div class="col-md-3">
<label>Designation</label>
<input type="text" class="form-control" name="designation" value="<?php echo esc_output($student_experience['designation']);?>">
</div>
<div class="col-md-3">
<label>Duration</label>
<input type="number" class="form-control" name="duration" value="<?php echo esc_output($student_experience['duration']);?>">
</div>
<div class="col-md-3">
<label>Employer</label>
<input type="text" class="form-control" name="employer" value="<?php echo esc_output($student_experience['employer']);?>">
</div>
</div>
<!-- additional content inserted here within common parent -->
</div>
</div>
<input type='hidden' name='duplicates' />

multiple dynamic input onchange and onblur function javascript

I have multiple input that when you select the option, the stock and the price would come out on other input to be used for another function.
i've tried to add unique id's for the inputs added but i just cant seem to figure out how to apply the function to the added inputs.
here is the Html:
<div id="container1">
<div class="form-group row">
<div class="col-lg-3">
<select class="form-control border-teal" id="produk_nama1" name="produk_nama[]">
<option value="">Pilih Produk</option>
#foreach ($stoks as $stok)
<option data-stok="{{$stok->stok}}" data-price="{{$stok->harga}}" value="{{$stok->produk->produk}}">{{$stok->produk->produk}}</option>
#endforeach
</select>
<div class="d-block form-text">
<span id="stok1" class="badge bg-orange"></span>
</div>
</div>
<div class="col-lg-3">
<input type="text" id="harga1" name="harga[]" class="form-control border-teal border-1" placeholder="Harga Produk" readonly>
</div>
<div class="col-lg-3">
<input type="number" id="jumlah1" name="jumlah[]" min="1" class="form-control border-teal border-1" placeholder="Masukkan Jumlah">
</div>
<div class="col-lg-3">
<input type="text" id="subtotal1" name="subtotal" class="form-control border-teal border-1" placeholder="Subtotal" readonly>
</div>
</div>
</div>
here is the javascript:
$(document).ready(function() {
var add_button = $("#add_button");
var inputs = document.getElementsByTagName('input');
var select = document.getElementById("produk_nama");
var i = 1;
$(add_button).click(function(e) {
e.preventDefault();
i++;
$("#container1")
var html = '<div class="form-group row">';
// select buah
html += '<div class="col-lg-3">';
html += '<select class="form-control border-teal" id="produk_nama'+i+'" name="produk_nama[]">';
html += '<option value="">Pilih Produk</option>';
html += '#foreach ($stoks as $stok)';
html += '<option data-stok="{{$stok->stok}}" data-price="{{$stok->harga}}" value="{{$stok->produk->produk}}">{{$stok->produk->produk}}</option>';
html += '#endforeach';
html += '</select>';
html += '<div class="d-block form-text">';
html += '<span id="stok'+i+'" class="badge bg-orange"></span>';
html += '</div></div>';
html += '<div class="col-lg-3">';
html += '<input type="text" id="harga'+i+'" name="harga[]" class="form-control border-teal border-1" placeholder="Harga Produk" readonly>';
html += '</div>';
html += '<div class="col-lg-3">';
html += '<input type="number" id="jumlah'+i+'" name="jumlah[]" min="1" class="form-control border-teal border-1" placeholder="Masukkan Jumlah">';
html += '</div>';
html += '<div class="col-lg-3">';
html += '<input type="text" id="subtotal'+i+'" name="subtotal" class="form-control border-teal border-1" placeholder="Subtotal" readonly>';
html += '</div>';
html += '</div>';
$(this).before(html);
// clone entire div
// $("#container1")
// .append(
// $("#container1")
// .children(inputs)
// .first()
// .clone()
// )
});
// main input function
$('#produk_nama'+i).on('change', function(){
alert(i);
var hargaproduk = $('#produk_nama'+i+' option:selected').data('price');
var stok = $('#produk_nama'+i+' option:selected').data('stok');
$('#stok'+i).text('Stok '+stok);
$('#harga'+i).val(hargaproduk);
});
document.getElementById('jumlah'+i).addEventListener("blur", function(){
var jumlah = $('#jumlah'+i).val();
var harga = $('#harga'+i).val();
var subtotal = jumlah * harga;
$('#subtotal'+i).val(subtotal);
})
});
any help and explanation would be much appreciated, thank you
As your first select-box i.e :produk_nama is same for all divs you can use clone() method to get clone of that select instead of writing laravel code inside jquery code.
Then , you can use $(document).on("change", "select[name*=produk_nama]".. to capture all change event on select-box . Inside this you can use .closest() and .find() method to get required values from input you needed and add the value to required inputs.Same you can do for jumlah input .
Demo Code :
$(document).ready(function() {
var add_button = $("#add_button");
var i = 1;
$(add_button).click(function(e) {
e.preventDefault();
i++;
$("#container1")
//get first div > selct clone it
var slects = $('.outer:first').find("select").clone();
var html = '<div class="form-group row outer">';
html += '<div class="col-lg-3">';
html += '<select class="form-control border-teal" id="produk_nama' + i + '" name="produk_nama[]">';
html += $(slects).html(); //add that
html += '</select>';
html += '<div class="d-block form-text">';
html += '<span id="stok' + i + '" class="badge bg-orange"></span>';
html += '</div></div>';
html += '<div class="col-lg-3">';
html += '<input type="text" id="harga' + i + '" name="harga[]" class="form-control border-teal border-1" placeholder="Harga Produk" readonly>';
html += '</div>';
html += '<div class="col-lg-3">';
html += '<input type="number" id="jumlah' + i + '" name="jumlah[]" min="1" class="form-control border-teal border-1" placeholder="Masukkan Jumlah">';
html += '</div>';
html += '<div class="col-lg-3">';
html += '<input type="text" id="subtotal' + i + '" name="subtotal" class="form-control border-teal border-1" placeholder="Subtotal" readonly>';
html += '</div>';
html += '</div>';
$(this).before(html);
});
//on change of selct
$(document).on("change", "select[name*=produk_nama]", function() {
//get attrs values
var hargaproduk = $(this).find("option:selected").attr('data-price');
var stok = $(this).find("option:selected").attr('data-stok');
//add the values to required elemnt
$(this).closest(".outer").find(".d-block span").text('Stok ' + stok)
$(this).closest(".outer").find("input[name*=harga]").val(hargaproduk);
});
$(document).on("blur", "input[name*=jumlah]", function() {
var jumlah = $(this).val(); //get value
var harga = $(this).closest(".outer").find("input[name*=harga]").val();
var subtotal = jumlah * harga;
//add value to subtotal
$(this).closest(".outer").find("input[name=subtotal]").val(subtotal);
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="container1">
<!--just added outer class-->
<div class="form-group row outer">
<div class="col-lg-3">
<select class="form-control border-teal" id="produk_nama1" name="produk_nama[]">
<option value="">Pilih Produk</option>
<option data-stok="something" data-price="12" value="1">1</option>
<option data-stok="something" data-price="13" value="2">2</option>
<option data-stok="something" data-price="14" value="3">3</option>
</select>
<div class="d-block form-text">
<span id="stok1" class="badge bg-orange"></span>
</div>
</div>
<div class="col-lg-3">
<input type="text" id="harga1" name="harga[]" class="form-control border-teal border-1" placeholder="Harga Produk" readonly>
</div>
<div class="col-lg-3">
<input type="number" id="jumlah1" name="jumlah[]" min="1" class="form-control border-teal border-1" placeholder="Masukkan Jumlah">
</div>
<div class="col-lg-3">
<input type="text" id="subtotal1" name="subtotal" class="form-control border-teal border-1" placeholder="Subtotal" readonly>
</div>
</div>
</div>
<button id="add_button">Add more</button>

Disable add more file inputs if the first it's empty, javascript

I'm working on a project that has the option to add attached files, you can add as many as you want, but I want to disable add more inputs if the first it's empty, the third if the second it's empty and so on...
HTML CODE:
<input type="hidden" name="file_count" value="1" id="file_count">
<div id="file_block">
<div class="form-group">
<label for="p-in" class="col-md-4 label-heading" style="margin-top:0px"><?php echo lang("ctn_438") ?></label>
<div class="col-md-8">
<input type="file" name="user_file_1" class="form-control">
</div>
</div>
</div>
<input type="button" name="s" value="<?php echo lang("ctn_439") ?>" class="btn btn-info btn-xs" onclick="add_file()">
Javascript
function add_file()
{
var count = $('#file_count').val();
count++;
var html = '<div class="form-group">'+
'<label for="p-in" class="col-md-4 label-heading"><?php echo lang("ctn_438") ?></label>'+
'<div class="col-md-8">'+
'<input type="file" name="user_file_'+count+'" class="form-control">'+
'</div>'+
'</div>';
$('#file_block').append(html);
$('#file_count').val(count);
}
Thanks!

Get all values in my added column using PHP (codeigniter)

I am studying the dbforge, and trying to apply it with my website. My basis or guide is the localhost/phpmyadmin where you will create a new table, i am done with the part of table name, name,type,attribute,length of the column and also the adding the column(see the picture below) .
Question: How can I retrieve all the post value?
Note: I tried to echo json_encode($_POST); im only getting 1 value.
View
<form id="new-table">
<div class="col-md-6">
<label>Table Name:</label>
<input type="hidden" name="type" value="new_table">
<input type="text" class="form-control border-input" name="table_name" id="table_name"><br>
<div class="text-danger" id="table_name_error"></div>
</div>
<!-- col-md-6 -->
<div class="col-md-3">
<label>Columns:</label>
<!-- <input type="text" class="form-control border-input" name="table_name" id="table_name"> -->
<input type="text" class="form-control border-input" id="number_of_column" >
</div>
<div class="col-md-3">
<br>
<button type="button" class="btn btn-info btn-fill btn-wd" onclick="addColumn()">Add</button>
</div>
<!-- col-md-3 -->
</div> <!-- row-->
<!-- <input type='button' value='Add Children' id='addButton' class="btn btn-sm btn-primary"> -->
<div class="row">
<div class="col-md-2">
<h6>Name</h6>
<input type="text" class="form-control border-input" name="field_name" id="field_name">
<div class="text-danger" id="field_name_error"></div>
</div>
<div class="col-md-2">
<h6>Type</h6>
<select class="form-control border-input" name="field_type" id="field_type">
<option value="volvo">Varchar</option>
<option value="saab">Int</option>
<option value="mercedes">Date</option>
<option value="audi">Text</option>
</select>
</div>
<div class="col-md-2">
<h6>Length/Value</h6>
<input type="text" class="form-control border-input" name="field_length" id="field_length">
<div class="text-danger" id="field_length_error"></div>
</div>
<div class="col-md-2">
<h6>Default</h6>
<input type="text" class="form-control border-input" name="field_default" id="field_default">
<div class="text-danger" id="field_default_error"></div>
</div>
<div class="col-md-2">
<h6>Attributes</h6>
<input type="text" class="form-control border-input" name="field_attributes" id="field_attributes">
<div class="text-danger" id="field_attributes_error"></div>
</div>
<div class="col-md-2">
<h6>Null</h6>
<input type="text" class="form-control border-input" name="field_null" value="null"><br>
<div class="text-danger" id="field_null_error"></div>
</div>
<div id="append">
<div id="TextBoxDiv1">
</div>
</div>
</div> <!-- row -->
<div class="text-right">
<button type="submit" class="btn btn-info btn-fill btn-wd">Update Profile</button>
</div>
</div>
<div class="clearfix"></div>
</form>
Controller
JS
My creating new column function
function addColumn()
{
var i = 0;
var columns = document.getElementById("number_of_column").value;
for(i=1;i<=columns;i++)
{
var newTextBoxDiv = $(document.createElement('div')).attr("id", 'TextBoxDiv' );
newTextBoxDiv.after().html('<div class="col-md-2">'+
'<label>Name</label>'+
'<input type="text" class="form-control border-input" name="field_name[]" id="field_name[]">'+
'<div class="text-danger" id="children_fname_error"></div>'+
'</div>'+
'<div class="col-md-2">'+
'<h6>Type</h6>'+
'<select class="form-control border-input" name="field_type[]" id="field_type[]">'+
'<option value="volvo">Varchar</option>'+
'<option value="saab">Int</option>'+
'<option value="mercedes">Date</option>'+
'<option value="audi">Text</option>'+
'</select>'+
'</div>'+
'<div class="col-md-2">'+
'<h6>Length/Value</h6>'+
'<input type="text" class="form-control border-input" name="field_length[]" id="field_length[]">'+
'<div class="text-danger" id="field_length_error"></div>'+
'</div>'+
'<div class="col-md-2">'+
'<h6>Default</h6>'+
'<input type="text" class="form-control border-input" name="field_default" id="field_default">'+
'<div class="text-danger" id="field_default_error"></div>'+
'</div>'+
'<div class="col-md-2">'+
'<h6>Attributes</h6>'+
'<input type="text" class="form-control border-input" name="field_attributes" id="field_attributes">'+
'<div class="text-danger" id="field_attributes_error"></div>'+
'</div>'+
'<div class="col-md-2">'+
'<h6>Null</h6>'+
'<input type="text" class="form-control border-input" name="field_null" id="field_null"><br>'+
'<div class="text-danger" id="field_null_error"></div>'+
'</div>'
);
newTextBoxDiv.appendTo("#append");
}
document.getElementById("number_of_column").value = "";
}
** My submit form**
$(document).ready(function(){
$("#new-table").on('submit',function(e){
$.ajax({
url: base_url+"formsubmit/new_form_submit",
type: "POST",
data: $(this).serialize(),
success:function(data)
{
var result = JSON.parse(data);
if(result === "success")
{
$("h5").html("");
success_message("#success-message-edit-content-1","Update Successfully!");
window.setTimeout(function(){location.href=base_url+"administrator/view_content"},2000);
}
else{
$("#table_name_error").html(result.table_name_error);
$("#field_name_error").html(result.field_name_error);
$("#field_type_error").html(result.field_type_error);
$("#field_length_error").html(result.field_length_error);
}
},
error: function(data) {
alert('error');
}
})
e.preventDefault();
})
})
In your code, I see you already have an input with name="field_name" and in the addColumn()
function you are also adding another input with the same name.
When you have a input named "field_name" in the form and later you again dynamically add another input with the same name again, they replaces one another and there is only one of their value present in the post data with that same name.
You can use array inputs here, like
<input name="field_name[]" ... />
<input name="field_type[]" ... />
...
<input name="field_name[]" ... />
<input name="field_type[]" ... />
...
<input name="field_name[]" ... />
<input name="field_type[]" ... />
...
You will get the Post array like:
Array
(
[field_name] => Array
(
[0] => fv1
[1] => fv2
....
)
[field_type] => Array
(
[0] => ftv1
[1] => ftv12
...
)
)
So for parsing:
$fields_array = array();
$no_of_fields = isset($_POST['field_name'])? count($_POST['field_name']) : 0;
for ($i=1; $i<=$no_of_fields; $i++) {
$tmp = array();
if (isset($_POST['field_name'][$i])) $tmp[] = $_POST['field_name'][$i];
if (isset($_POST['field_type'][$i])) $tmp[] = $_POST['field_type'][$i];
...
if (!empty($tmp)) $fields_array[] = array();
}
It is a little bit errorprone(assuming field_name, field_type will have arrays of same number of elements, if one is missing the parallel serial among them will be corrupted) approach.
Better to use counter for the fields.
For example:
<input name="no_of_fields" value="1"/>
Which's value will be increased in each addition.
And your form be like:
<input name="field_name_1" .../>
<input name="field_type_1" .../>
...
<input name="field_name_2" .../>
<input name="field_type_2" .../>
...
<input name="field_name_3" .../>
<input name="field_type_3" .../>
...
For parsing on the server side, you can go for:
$fields_array = array();
$no_of_fields = isset($_POST['no_of_fields'])? intval($no_of_fields) : 0;
if ($no_of_fields > 0) {
for ($i=1; $i<=$no_of_fields; $i++) {
$tmp = array();
if (isset($_POST['field_name_'.$i])) $tmp[] = $_POST['field_name_'.$i];
if (isset($_POST['field_type_'.$i])) $tmp[] = $_POST['field_type_'.$i];
...
if (!empty($tmp)) $fields_array[] = array();
}
}
// Now process/output the $fields_array;

How to validate if all textbox value is not empty in an array name using jquery?

I have a problem in my form. In my form the user can add multiple discount codes. And what I need to validate are the two textboxes these are 'date start' and 'date expired' and I need to find out if these are empty. Before allowing the user to add another row again.
Here's my code:
function addProductDiscountCode() {
var html = '<tr id="row-count-' + iterator + '">';
html += ' <td>';
html += ' <input type="text" name="discount_code[' + iterator + '][code]" class="form-control" readonly="readonly" value="' + code + '" />';
html += ' </td>';
html += ' <td class="text-center">';
html += ' <input type="text" name="discount_code[' + iterator + '][percentage]" class="form-control text-center" />';
html += ' </td>';
html += ' <td class="text-center">';
html += ' <div class="input-group date"><input name="discount_code[' + iterator + '][date_start]" value="" id="start-date-' + iterator + '" placeholder="YYYY-MM-DD" data-date-format="YYYY-MM-DD" class="form-control date_set" type="text" readonly><span class="input-group-btn"><button type="button" class="btn btn-default"><i class="fa fa-calendar"></i></button></span></div>';
html += ' </td>';
html += ' <td class="text-center">';
html += ' <div class="input-group date"><input name="discount_code[' + iterator + '][date_expired]" value="" id="end-date-' + iterator + '" placeholder="YYYY-MM-DD" data-date-format="YYYY-MM-DD" class="form-control date_end" type="text" readonly><span class="input-group-btn"><button type="button" class="btn btn-default"><i class="fa fa-calendar"></i></button></span></div>';
html += ' </td>';
html += ' <td style="width: 15%">';
html += ' <select class="form-control" name="discount_code[' + iterator + '][status ]">';
html += ' <option value="0">Disable</option>';
html += ' <option value="1">Activate</option>';
html += ' </select>';
html += ' </td>';
html += ' <td class="text-center"><button type="button" onClick="removeCode(' + iterator + ');" class="btn btn-danger"><i class="fa fa-minus-circle"></i></button></td>';
html += '</tr>';
$("#product-discount-code tbody").append(html);
iterator++;
$('.date').datetimepicker({
pickTime: false
});
}
And this will result in a row like this:
<tr id="row-count-1">
<td>
<input name="discount_code[1][code]" class="form-control" readonly="readonly" value="4npi7YIIrv" type="text">
</td>
<td class="text-center">
<input name="discount_code[1][percentage]" class="form-control text-center" type="text">
</td>
<td class="text-center">
<div class="input-group date">
<input name="discount_code[1][date_start]" value="" id="start-date-1" placeholder="YYYY-MM-DD" data-date-format="YYYY-MM-DD" class="form-control date_set" readonly="" type="text">
<span class="input-group-btn">
<button type="button" class="btn btn-default"><i class="fa fa-calendar"></i></button>
</span>
</div>
</td>
<td class="text-center">
<div class="input-group date">
<input name="discount_code[1][date_expired]" value="" id="end-date-1" placeholder="YYYY-MM-DD" data-date-format="YYYY-MM-DD" class="form-control date_end" readonly="" type="text">
<span class="input-group-btn">
<button type="button" class="btn btn-default"><i class="fa fa-calendar"></i></button>
</span>
</div>
</td>
<td style="width: 15%">
<select class="form-control" name="discount_code[1][status ]">
<option value="0">Disable</option>
<option value="1">Activate</option>
</select>
</td>
<td class="text-center">
<button type="button" onclick="removeCode(1);" class="btn btn-danger">
<i class="fa fa-minus-circle"></i>
</button>
</td>
</tr>
I added a console print in the add action:
$(".date_start").val();
$(".date_end").val();
And It only get the value of the first row. I need
The getter method like .val(), in jQuery will return the value of the first element in the set not of all the elements(with exceptions like .text())
You can use a loop based logic to see whether all the elements has values
var date_set = true;
$('.date_set').each(function () {
if ($(this).val().length == 0) {
date_set = false;
return false;
}
})

Categories

Resources