Loop through fields in a form - javascript

Assume I have a table. Each row contains form fields that can be populated or not by the user. I need to check that for each row either all the form fields are populated or none.
The html is this:
<tr class="riga_gar">
<td class="report">
<input type="hidden" id="crediti[<?php echo $i; ?>]" name="crediti[<?php echo $i; ?>]"
value="<?php echo $cred['id_cre']; ?>" >
<?php echo $cred['id_cre'] ?>
</td>
<td class="report gbv" data-gbv="<?php echo $cred['gbv_tot']; ?>">
<?php echo num2cur($cred['gbv_tot']); ?>
</td>
<td class="report">
<?php echo veicolo2name($cred['titolare'],$pdo); ?>
</td>
<td class="report">
<?php echo $cred['stato']; ?>
</td>
<td class="report">
<input class="input_field numerico" id="chiesto" type="text" name="garanzia[<?php echo $i; ?>]" value="<?php echo $chiesto; ?>">
</td>
<td class="report">
<select name="tipo_gar[<?php echo $i; ?>]">
<option value="">Scegli</option>
<?php foreach($tipo_gars as $tipo_gar){
echo '<option value="'.$tipo_gar['id'].'">'.$tipo_gar['descrizione'].'</option>';
}?>
</select>
</td>
</tr>
What I am trying to do is to check that for each row both the input and the select have a value or none.
I started with this js:
function ajax_submit(){
var submit_val=$("#garante").serialize();
dest="anagrafiche/new_garante1.php";
$('.riga_gar').each(function(i,obj){
if ($(this).val()!='') {
}
});
}
and I want to run this ajax function:
$.ajax({
type: "POST",
url: dest,
data: submit_val,
success: function(data){
data1=data.split("|");
if(data1[0]=="Successo"){
$("#spnmsg").fadeTo(200,0.1,
function(){$(this).removeClass().addClass("spn_success").html(data1[1]).fadeTo(900,1)});
}else if(data1[0]=="Errore"){
$("#spnmsg").fadeTo(200,0.1,
function(){$(this).removeClass().addClass("spn_error").html(data1[1]).fadeTo(900,1)});
}
},
complete: function(){
$.fancybox.close();
//setTimeout(function(){ $('.container').load('sofferenze/dashboard.php?from=<?php echo $id_soff ?>');},3000);
setTimeout(function(){
$('#upper').load('sofferenze/soff.php?soff=<?php echo $id_soff ?>');
$("#spnmsg").fadeTo(200,0.1,
function(){$(this).removeClass().addClass("spn_normal").html('Cruscotto della sofferenza <?php echo soff2name($id_soff,$pdo); ?>').fadeTo(900,1)});
},3000);
} //chiudo complete function
}); //chiudo $.ajax
only when:
at least one row have both values;
all the rows that have values have both of them;
but I get stuck at how to refer to the value of input and select in the each loop so that I can check my conditions.

I think this will help you. This will read each row and ignore your hidden field. Once code will find both values populated than validateForm variable will be true and will become false if in next row one value from both input or select will be empty.
$(document).ready(function(){
var validateForm = false;
var check = 0;
$("form").on('submit',function(){
$("tr").each(function(){
console.log($.trim($(this).find("input.input_field").val()) +", "+ $.trim($(this).find("select").val()));
if($.trim($(this).find("input.input_field").val()) != "" && $.trim($(this).find("select").val()) != ""){
validateForm = true;
}
else{
if($.trim($(this).find("input.input_field").val()) == "" && $.trim($(this).find("select").val()) != ""){
if(validateForm){
validateForm = false;
check = 1;
return false;
}
}
if($.trim($(this).find("input.input_field").val()) != "" && $.trim($(this).find("select").val()) == ""){
if(validateForm){
validateForm = false;
check = 1;
return false;
}
}
}
});
if(validateForm && check == 0){
validateForm = true;
}
else{
validateForm = false;
}
if(validateForm){
//call ajax
}
});
});
Demo:https://jsfiddle.net/87tkraas/

This is untested but how about something like this:
var allowSubmit = false;
$("form").on("submit", function(e) {
$("tr").each(function() {
var input = $(this).find("input").val();
var select= $(this).find("select").val();
if ((input == "" && select != "") || (input != "" && select == "")) {
return;
} else if (input != "" && select != "") {
allowSubmit = true;
}
});
if (allowSubmit == false) {
e.preventDefault();
}
});

Related

Insert multiple records in single checkbox in codeigniter?

I've two different table, 1st is draft_table, and 2nd is fix_table, each table have same fields ( product & price )
i want to make data from draft_table, can be save to fix_table with checkbox, so just selected data will save to fix_table.
i've code like this :
AJAX
<script>
$(function(){
$("a.paid").click(function(){
if(confirm("Are you sure want save this?"))
{
id_array=new Array()
i=0;
$("input.chk:checked").each(function(){
id_array[i]=$(this).val();
i++;
})
$.ajax({
url:'<?php echo base_url(); ?>fix_data/set',
data:"kode="+id_array,
type:"POST",
success:function(respon)
{
if(respon==1)
{
window.parent.location.reload(true);
}
}
})
}
return false;
})
})
</script>
Views :
<?php
foreach($data_get->result_array() as $dp)
{
?>
<tr><td><input type="checkbox" name="chk[]" class="chk" value="<?php echo $dp['id_draft']; ?>" /></td>
<td><?php echo $dp['product']; ?></td>
<td><?php echo $dp['price']; ?></td>
</td></tr>
<?php
}
?>
Controller :
public function set_stts()
{
if($this->session->userdata('logged_in')!="")
{
$id_get = $this->input->post('kode');
$dt = $this->db->get_where("tbl_draft",$id_get)->row();
$product = $dt->product;
$price = $dt->price;
if ($this->input->post('kode')) {
$query = $this->db->query("INSERT INTO tbl_fix (product,price) VALUES (".$product.",".$price.")");
}
if($query){
echo 1;
}
else{
echo 0;
}
}
else
{
header('location:'.base_url().'dashboard_item');
}
}
After i Click submit in draft form, nothing happen, is there anyone may help me with this case?
Thank you
maybe you can change your controller like this :
public function set()
{
if($this->session->userdata('logged_in')!="")
{
$id_get = $this->input->post('kode');
$quer = $this->db->query("select * from tbl_draft WHERE id IN (".$id_get.")");
if ($this->input->post('kode')) {
foreach($quer->result_array() as $dp)
{
$a = $dp['product'];
$b = $dp['price'];
$query = $this->db->query("INSERT INTO tbl_fix (product,price) VALUES
('".$a."','".$b."')");
}
}
if($query){
echo 1;
}
else{
echo 0;
}
}
else
{
header('location:'.base_url().'dashboard_item');
}
}

how create if for option in select?

How can I create if for option in select? The code works, it is necessary to code only worked for option = 5
<select id="select<?php echo $product['id_product'];?>" name="status_id" class="form-control" onchange="changeFunction(<?php echo $product['id_product'];?>)">
<?php foreach ($statuses as $status) { ?>
<option id="option<?php echo $product['id_product'];?>" value="<?php echo $status['id_product_status'];?>"
<?php if ($status['id_product_status'] == $product['id_product_status']) { ?> selected="selected"<?php } ?>>
<?php echo $status['name_product_status']; ?>
</option>
<?php } ?>
<textarea id="onchange<?php echo $product['id_product'];?>" style="visibility: hidden" "></textarea>
</select>
function changeFunction(item) {
if ($("#option" + item).val == 5) {
var selectOption = document.querySelector("#onchange" + item);
selectOption.setAttribute('style', 'visibility: visible');
}
}
Do like this, though you don't need to pass "item" as parameter to achieve this. When you select an option, a change event is triggered on select. So you can bind a change event for this particular requirement. Upto you.
function changeFunction(item){
if($("#select"+item).val() == 5) {
var selectOption = $("select option:selected");
selectOption.setAttribute('style', 'visibility: visible');
}
}
you can use this code :
function changeFunction(item){
if($(this).val() == 5) {
$(this).css('visibility': 'visible');
}
}

how to select id which is dynamically change in jquery?

here is my html:
<?php echo ($row['status'] == 1)? ?>
<span id='slide_".$row['id']."' name="slid_id" class='label label-danger'>Inactive</span>
<?php : ?>
<span id='slide_".$row['id']."' name="slid_id" class='label label-success'>Active</span>
<?php ; ?>
here is my jquery code:
$(document).ready(function()
{
$("span").click(function()
{
var id = $(":input[name=slide_id]").val();
alert(id);
});
});
i didn't get anything , i want to get the
ID & its dynamic generated value
of the span element and then perform some action like on click i want to change the status from active to inactive or vise versa.
thanks in advance.
var id = $(":input[name=slide_id]").attr('id'); should do the job. .val() only returns the current value of input elements.
Your HTML is missing from the question, but eliminating the colon in your jQuery selector might do the trick in selecting an input field - i.e. $("input[name=slide_id]").val().
If you want to get the ID attribute of a span element, this would work:
$('span_selector').attr('id');
okay finally i got the way to solve this things. m just sharing this if anyone have same issue one day then this might helpful.
html codes:
<tr class="tr">
<td class="td">
<div id="status">
<?php
echo ($row['status'] == 1)?
"<span id='".$row['id']."' class='label label-danger'>Inactive</span>":
"<span id='".$row['id']."' class='label label-success'>Active</span>";
?>
</div>
</td>
</tr>
my jquery code:
$(document).ready(function()
{
$("#status > span") .click(function()
{
var id = $(this).attr('id');
var tempelement = $(this);
var texts = $(this).closest(".tr").find("#texts").val();
var author = $(this).closest(".tr").find("#author").val();
var status = $(this).text();
$.ajax({
type: 'POST',
url: 'manage_feedback.php',
data: {id:id, texts:texts, author:author, status:status},
success: function(data)
{
if (data == "Active")
{
$(tempelement).removeClass("label label-danger");
$(tempelement).addClass("label label-success");
$(tempelement).html(data);
alert('status changed');
}
else if (data == "Inactive")
{
$(tempelement).removeClass("label label-success");
$(tempelement).addClass("label label-danger");
$(tempelement).html(data);
alert('status changed');
}
else
{
alert(data);
}
}
});
});
php script
//ajax status changer code
if (isset($_POST['id']) && isset($_POST['texts']) && isset($_POST['status']) && isset($_POST['author']))
{
$id = $_POST['id'];
$texts = trim($_POST['texts']);
$author = trim($_POST['author']);
$status = $_POST['status'];
$qry = "SELECT count(id) as count FROM tbl_testimonials WHERE texts = '".$texts."'
AND author = '".$author."' AND id != ".$id." ";
$sql = mysql_query($qry);
$data = mysql_fetch_assoc($sql);
if ($data['count'] == 0)
{
if($status == 'Inactive')
{
$qry = "UPDATE tbl_testimonials SET status = 0 WHERE id = ".$id." " ;
$sql = mysql_query($qry);
if($sql == 1)
{
echo 'Active';
exit;
}
}
elseif ($status == 'Active')
{
$qry = "UPDATE tbl_testimonials SET status = 1 WHERE id = ".$id." " ;
$sql = mysql_query($qry);
if($sql == 1)
{
echo 'Inactive';
exit;
}
}
}
else
{
echo "name already taken";
exit;
}
}
hope it will help someone.

Show/hide Div when select option value

When echo inside value the javascript onchange doesnt work. it must click/choose again to show the div.
<?php
$test = '1';
?>
<select name="request" id="reqtypev" class="form-control1" >
<option value="<?php echo $test ?>" selected="selected"><?php echo $test ?></option>
</select>
it does work if you didnt echo it using php.
//javascript
$('#reqtypev').change(function(){
if( $(this).val()==="1" || $(this).val()==="2" || $(this).val()==="3" || $(this).val()==="4" ){
$("#otherTypev").show()
} else {
$("#otherTypev").hide()
}
});
how is it possible to execute the javascript when you echo using php ?
Trigger change event after page load for #reqtypev as following:
(function ($) {
$(function () {
$('#reqtypev').change(function(){
if( $(this).val()==="1" || $(this).val()==="2" || $(this).val()==="3" || $(this).val()==="4" ){
$("#otherTypev").show()
} else {
$("#otherTypev").hide()
}
});
$('#reqtypev').trigger("change");
});
}(jQuery));
Try this :
<?php
$test = '1';
?>
<select name="request" id="reqtypev" class="form-control1" onchange="intializeDrop(this.value);" >
<option value="<?php echo $test ?>" selected="selected"><?php echo $test ?></option>
</select>
Js code:
function intializeDrop(id){
if( $(this).val()==="1" || $(this).val()==="2" || $(this).val()==="3" || $(this).val()==="4" ){
$("#otherTypev").show()
} else {
$("#otherTypev").hide()
}
}
Try this
//javascript
$(document).on('change','#reqtypev',function(){
if( $(this).val()==="1" || $(this).val()==="2" || $(this).val()==="3" || $(this).val()==="4" ){
$("#otherTypev").show()
} else {
$("#otherTypev").hide()
}
});
Hmm, I don't think it's doable in PHP, PHP executes once and quits (Until another refresh occurs)
You can do it in PHP, once. But not live where people are moving the selection bar around.
Can you put more info on what you want to do? I assume from the little code you are showing is to hide a field in the form once a person chooses a value < 1 or > 4
Value in option at least 2 values function change() to activity
<div id="otherTypev">texttttt</div>
<select name="request" id="reqtypev" class="form-control" >
<?php
for($i = 0;$i<=10;$i++){
echo '<option value="'.$i.'" selected="selected">'.$i.'</option>';
}
?>
</select>
Js
<script>
$('#reqtypev').change(function(){
if( $(this).val()=== "1" || $(this).val()==="2" || $(this).val()==="3" || $(this).val()==="4" ){
$("#otherTypev").show()
} else {
$("#otherTypev").hide()
}
});
</script>

jQuery form validation with PHP variables

I'm working on a form validation with PHP variables, just to not repeat myself in HTML when it comes to displaying default values of text inputs & textareas. Basically, what I want to achieve, is that each field has it's own default value, which disappears on focus and appears back on blur, if user hasn't typed anything in.
Then it validates, if user hasn't left fields with default values (which would make default values red, to bring users focus to them). After submitting, form slides up and shows div#thanks with button allowing to show the form again, with text area cleared.
Validation is working ok without PHP variables (there is also server side validation, in case of switched off JS).
PS. Also form appears after clicking on a#opt4, but that part works fine, too.
PS2. My head is melted at this stage, so wouldn't be surprised if there is some ridiculous bugs, just to warn you
$(document).ready(function() {
<!--
<?php
$defaultMsg = "Please type in your message";
$defaultEmail = "Your Email";
$defaultName = "Your name (optional)";
?>
-->
$('#contact-form').hide();
$('a#opt4').click(function (e) {
e.preventDefault();
$('#contact-form').slideToggle("normal", function() {
if ( $(".mobile-sp").css("display") === "none") {
$('html, body').toggleState(function (el) {
el.animate({
scrollTop: $("#anchor").offset().top
}, 800);
}, function (el) {
});
}
});
$('textarea, input[type="text"]').focus(function() {
if ( $(this).hasClass('error')) {
$(this).removeClass('error');
}
var text = $(this).val();
$(this).animate({
color: "#fff"
},400, function () {
if ((text === <?php echo $defaultMsg; ?>) || (text === <?php echo defaultEmail; ?>)) {
$(this).val("");
}
});
});
$('textarea, input[type="text"]').blur(function() {
$(this).animate({
color: "#6599cb"
},400, function () {
if ($.trim(this.value) == '') {
$(this).val(this.defaultValue);
}
});
});
});
// validation
$("#thanks").hide();
$("#submit").click(function(e) {
e.preventDefault();
});
$("#submit").click(function(){
$(".error").hide();
$("#one-more").hide();
var hasError = false;
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
var emailFromVal = $("#emailFrom").val();
var defaultEmail = <?php echo $defaultEmail; ?>;
if((emailFromVal == '') || (emailFromVal === defaultEmail)) {
$("#email").val('defaultEmail');
hasError = true;
} else if(!emailReg.test(emailFromVal)) {
$("#email").val('defaultEmail');
hasError = true;
}
var messageVal = $("#message").val();
var defaultMsg = <?php echo $defaultMsg; ?>;
if((messageVal == '') || (messageVal === defaultMsg)) {
$("textarea").val('#message'.defaultValue).addClass('error');
hasError = true;
}
if(hasError == false) {
$(this).hide();
$("#sendEmail button").append('<img src="modules/contact/loading.gif" alt="Loading" id="loading" />');
$.post("modules/contact/sendEmail.php",
{ emailFrom: emailFromVal, message: messageVal },
function(data){
$("#sendEmail").slideUp("normal", function() {
$("#thanks").slideDown("normal", function() {
$("#one-more").slideDown("slow");
});
});
}
);
}
return false;
});
$("#one-more").click(function(e) {
e.preventDefault();
var defaultMsg = <?php echo $defaultMsg; ?>;
$('#thanks').slideUp("slow",function() {
$('form').slideDown('slow', function() {
$('#submit').show();
$('#message').val('defaultMsg');
});
});
});
});
// HTML
<div id="form">
<?php include('modules/contact/verify.php'); ?>
<h2>Talk to us about your project</h2>
<form action="" method="post" id="sendEmail">
<textarea name="message" id="message"><?php if(isset($_POST['message'])) { echo $_POST['message']; } else { echo $defaultMsg; } ?></textarea><?php if(isset($messageError)) echo '<span class="error">'.$messageError.'</span>'; ?>
<input type="text" name="emailFrom" id="emailFrom" value="<?php if(isset($_POST['emailFrom'])) { echo $_POST['emailFrom']; } else { echo $defaultEmail; } ?>"><?php if(isset($emailFromError)) echo '<span class="error">'.$emailFromError.'</span>'; ?>
<input type="text" name="name" id="name" value="<?php echo $defaultName; ?>">
<input type="submit" id="submit" value="Send">
<input type="hidden" name="submitted" id="submitted" value="true">
</form>
<div id="thanks">
<div class="container">
<img src="gfx/sprites/icn-contact-success.png">
<h3>Thank you.</h3>
<p>We will get back to you as soon as possible.</p>
</div>
Oh no, wait! I want to add something!
</div>
</div>

Categories