Issue hiding fields on multiple rendered form - javascript

I am trying to render a form for each person that I get based on a specific input from the database.
#forelse($driverNames as $driver)
<form id="inspection_report_form" enctype="multipart/form-data" action="/inspection-report/store" method="POST">
#csrf
I am trying to hide some fileds if no is selected from dropdown.
<div class="row">
<div class="col-lg-2">
<div class="form-group">
<label>Equipment</label>
<div class="input-group mb-3">
<select class="custom-select" id="branded_equipment" name="branded_equipment" required>
<option value="">Select</option>
<option value="yes">Yes</option>
<option value="no">No</option>
</select>
</div>
</div>
</div>
<script>
let branded_equipment = document.getElementById('branded_equipment');
branded_equipment.addEventListener('change', function () {
if (branded_equipment.value === 'no') {
document.getElementById('branded_equipment_picture').required = false;
document.getElementById('branded_equipment_picture').disabled = true;
document.getElementById('branded_equipment_picture').style.display = 'none';
document.getElementById('branded_equipment_picture_label').style.display = 'none';
} else {
document.getElementById('branded_equipment_picture').required = true;
document.getElementById('branded_equipment_picture').disabled = false;
document.getElementById('branded_equipment_picture').style.display = 'block';
document.getElementById('branded_equipment_picture_label').style.display = 'block';
}
});
</script>
The problem that I am facing is that it works only for the first form in the list , if i am clicking on the next person form on the same dropdown id does nothing.
Same with the spinner
>! html
<div class="float-right">
{{--loader--}}
<button class="btn btn-primary" type="button" style="display: none" disabled id="spinner">
<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span>
Loading ...
</button>
<button class="btn btn-success" id="report_submit_btn">Save</button>
</div>
>! javascript
let report_submit_btn = document.getElementById('report_submit_btn');
report_submit_btn.addEventListener('click', function () {
report_submit_btn.style.display = 'none';
document.getElementById('spinner').style.display = 'block';
});
I am assuming that because of the form is generated multiple times and the dropdown is having the same id for each iteration it does not know how to make the difference after the first form.
Much appreciated if anyone can help.
I have tryied using multiple selectors or techniques but nothing works. I am wondering if is achievable what I am trying to do or I should try something different.

Related

jQuery. Wait input values in modal Bootstrap

I got a script that show modal bootstrap and get input values to operate with him. But my problem is that script dont stop the input values inserted by user.
MODAL:
<!-- Modal -->
<div class="modal fade" id="imageModal">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-body">
<div class="row">
<div class="col-12 col-sm-12 col-md-6 form-group">
<label for="f-type_id">Type image</label>
<select class="form-control">
<option value="">- Please select -</option>
#foreach($types as $type)
<option id="type_id" value="{{ $type->id
}}">
{{ $type->name }}
</option>
#endforeach
</select>
</div>
</div>
<div class="col-12 col-sm-12 col-md-6 form-group">
<label for="main">
<input type="checkbox" class="form-control"
id="main">
Main Image?
</label>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn data-target='#imageModal'
data-toggle='modal'>Save
</button>
</div>
</div>
</div>
And Script:
var $listOfImages = $('#listOfImages');
$('#addImageButton').click(function() {
FileManagerFunctions.open('images', function(url, filePath) {
// Add image element
$('#imageModal').modal('show');
var $type = $('#type_id').val();
var $main = $('#main').val();
var $newImage = imageHtml(filePath, $type, $main);
$listOfImages.append($newImage);
});
});
imageHtml is a function that make an arrray with these values (#type_id & #main) but I need stop ejecution of script until user insert $type & $main values
May be is possible stop script until modal are closed? No idea...
If I use debug browser I can check that variable values are passing to function imageHtml before that user insert values
Thanks in advance!
If I am understanding your question correctly, you could just do any checks you need to $type and $main before you run your function.
e.g.
var $listOfImages = $('#listOfImages');
$('#addImageButton').click(function() {
FileManagerFunctions.open('images', function(url, filePath) {
// Add image element
$('#imageModal').modal('show');
var $type = $('#type_id').val();
var $main = $('#main').val();
var $newImage = imageHtml(filePath, $type, $main);
if ($type !== '' && $main !== '') {
$listOfImages.append($newImage);
} else {
alert('please enter a value for name and type')
}
});
});
EDITED:
This resolve problem in part.
I added id="addImageData" in button modal and now rest of script wait modal closing. But problem now is value input arent correct. This solution is bad and doesnt work correctly. But May be is a idea that I need...

Select Option Doesn't Set on Button Click with jQuery

I've tried following a couple of answers with no success. I am trying to get the select box to go back to the "Please Select One Option" when the Add Exercise button is clicked. I got it to work in a simple scenario like this:
<div id="retro_add_exercises">
<div class="row">
<div class="input-field col s12">
<div class="select-wrapper initialized">
<select class="initialized" id="exercise_category">
<option value="0" disabled="" selected="">Please Select One</option>
<option value="1">Cardio</option>
<option value="2">Weight Lifting</option>
<option value="3">Stretching</option>
</select>
</div>
</div>
</div>
<!-- CARDIO SELECT FIELD -->
<div class="row" id="select_cardio">
<form method="POST" id="cardio_form">
<div class="input-field col s12">
<button class="btn waves-effect waves-light" id="add_exercise_from_cardio" type="submit" name="action" value="ADD">Add Exercise from cardio</button>
</div>
</form>
</div>
<script type="text/javascript">
$(document).ready(function() {
$('#add_exercise_from_cardio').click(function() {
$('#exercise_category').val('0').change();
});
});
</script>
But in my main project, it isn't working when I have the row show and hide on button click too. Any help would be appreciated.
$(document).ready(function() {
$('#retroactive_date_form').submit(function(e) {
e.preventDefault();
var date = $('#retroactive_date_picker');
var exercise_date = date.val();
if (exercise_date !== '') {
var exercise_category;
var weight_set_type;
console.log(exercise_date);
date.prop('disabled', true);
$('#retroactive_date_submit').addClass('disabled');
$('#retro_add_exercises').show();
//Exercise Category Function
$('#exercise_category').on('change', function() {
exercise_category = $('#exercise_category').val();
console.log(exercise_category);
if (this.value === '1')
{
$('#select_cardio').show();
$('#drop_or_reg_set_select_exercise').hide();
$('#super_set_select_exercises').hide();
$('#drop_and_regular_set_action_btn').hide();
$('#super_set_action_btn').hide();
$('#super_set_table_row').hide();
$('#drop_or_reg_set_table_row').hide();
}
else
$('#select_cardio').hide();
if (this.value === '2')
{
$('#select_weight').show()
}
else
$('#select_weight').hide();
if (this.value === '3')
{
$('#select_stretch_fields').show();
$('#select_cardio').hide();
$('#drop_or_reg_set_select_exercise').hide();
$('#super_set_select_exercises').hide();
$('#drop_and_regular_set_action_btn').hide();
$('#super_set_action_btn').hide();
$('#super_set_table_row').hide();
$('#select_weight').hide();
$('#drop_or_reg_set_table_row').hide();
}
else
$('#select_stretch_fields').hide();
return exercise_category;
});
///////////Cardio Training Functions///////////////
//Selecting Cardio Exercise
$('#cardio_exercise').on('change', function (e) {
var cardio_exercise;
cardio_exercise = $('#cardio_exercise').val();
console.log(cardio_exercise);
});
//Adding Another Exercise After Done Adding Current Cardio Exercise
$('#add_exercise_from_cardio').on('click', function(e) {
e.preventDefault();
$('#exercise_category option[value="0"]').attr('selected', true);
$('#select_cardio').hide();
$('#drop_or_reg_set_select_exercise').hide();
$('#super_set_select_exercises').hide();
$('#drop_and_regular_set_action_btn').hide();
$('#super_set_action_btn').hide();
$('#super_set_table_row').hide();
$('#drop_or_reg_set_table_row').hide();
});
//Error Handling If No Date is Selected Before Starting
else {
alert('Please select date')
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="retro_add_exercises" style="display:none">
<div class="row">
<div class="input-field col s12">
<div class="select-wrapper initialized"><span class="caret">▼</span>
<select class="initialized" id="exercise_category">
<option value="0" disabled="" selected="">Please Select One</option>
<option value="1">Cardio</option>
<option value="2">Weight Lifting</option>
<option value="3">Stretching</option>
</select>
</div>
<label>Choose Exercise Type</label>
</div>
</div>
<!-- CARDIO SELECT FIELD -->
<div class="row" style="display:none" id="select_cardio">
<form method="POST" id="cardio_form">
<div class="input-field col s12">
<div class="select-wrapper initialized"><span class="caret">▼</span>
<select id="cardio_exercise" name="cardio_exercise" class="initialized">
<option value="0" disabled selected>Choose Cardio Exercise</option>
<option value="1">Jumping Jacks</option>
<option value="2">Jump Rope</option>
<option value="3">Precor</option>
<option value="4">Running (outside)</option>
<option value="5">Swimming</option>
<option value="6">Treadmill</option>
</select>
</div>
<input type="date" style="display:none" id="cardio_exercise_date" name="cardio_exercise_date">
<input placeholder="Duration (minutes)" name="cardio_duration" id="cardio_duration" type="number" class="validate">
<input placeholder="Distance (optional)" name="cardio_distance" id="cardio_distance" type="number" class="validate">
<button class="btn waves-effect waves-light" id="add_exercise_from_cardio" type="submit" name="action" value="ADD">Add Exercise</button>
<button class="btn waves-effect waves-light" id="finish_tracking" type="submit" name="action" value="FINISH">Finish Workout</button>
<label for="cardio_exercise">Choose Exercise</label>
</div>
</form>
</div>
The jQuery documentation dictates that since jQuery 1.6, attr will not update the dynamic state of a DOM element. In addition, it appears your select is disabled after being selected. Try:
$('#exercise_category option[value="0"]').prop('disabled', false);
$('#exercise_category option[value="0"]').prop('selected', true);
There is probably a better and more efficient way to solve it, but I figured it out. I wrapped the select option in form wrappers and gave the form an ID. Then on the button click I triggered reset of the form using
$('#button_id').on('click', function(e) {
e.preventDefault();
$('#form_id').trigger('reset');
});
Although I'm sure there is a better way, this method worked for me and hopefully it works for someone else too.

submit a form and prevent from refreshing it

i'm working on a email sending function on a project. here when i fill the form and after sending it the web site page getting refresh and showing white background page. i need to prevent that from the refreshing and submit the form. here i'l attach the codes and can someone tell me the answer for this question.
HTML code for form
<form class="form-vertical" onsubmit="return sendEmail();" id="tell_a_friend_form" method="post" action="index.php?route=product/product/tellaFriendEmail" enctype="multipart/form-data">
<div class="form-group ">
<label class="control-label ">Your Name <span >* </span> </label><br>
<div class="form-group-default">
<input type="text" id="senders_name" name="sender_name" value="" class="form-control input-lg required" >
</div>
</div>
<div id="notify2" class="">
<div id="notification-text2" class="xs-m-t-10 fs-12"></div>
<!--<button type="button" class ="close" id="noti-hide">×</button>-->
</div>
<div class="form-group ">
<label class="control-label ">Your Email <span >* </span> </label><br>
<div class="form-group-default">
<input type="text" id="sender_email_ID" name="sender_email" value="" class="form-control input-lg" >
</div>
</div>
<div id="notify1" class="">
<div id="notification-text1" class="xs-m-t-10 fs-12"></div>
<!--<button type="button" class ="close" id="noti-hide">×</button>-->
</div>
<div class="form-group ">
<label class="control-label">Your Friends' Email <span >* </span></label>
<p class="lineStyle">Enter one or more email addresses, separated by a comma.</p>
<div class="form-group-default">
<input type="text" value="" id="receiver_email" class="form-control required" name="receivers_email" >
</div>
</div>
<div id="notify" class="">
<div id="notification-text" class="xs-m-t-10 fs-12"></div>
<!--<button type="button" class ="close" id="noti-hide">×</button>-->
</div>
<div >
<label domainsclass="control-label ">Add a personal message below (Optional) <br></label>
<div class="form-group-default">
<textarea type="text" id="tell_a_friend_message" name="tell_a_friend_message" class="form-control" rows="10" col="100" style=" width: 330px; height: 100px;"></textarea>
</div>
</div>
<div id="notify3" class="">
<div id="notification-text3" class="xs-m-t-10 fs-12"></div>
<!--<button type="button" class ="close" id="noti-hide">×</button>-->
</div>
<input type="hidden" name="product_url" id="product_url_field" value="">
<div class="p-t-15 p-b-20 pull-right">
<button id="send_mail_button" class="btn btn-rounded btn-rounded-fl-gold text-uppercase" name="submit" onclick="return sendEmail();" >Send</button>
<button id="cancel_email_form" class="btn btn-rounded btn-rounded-gold text-uppercase btn-margin-left" data-dismiss="modal" aria-hidden="true" >Cancel</button>
</div>
javascript code:
<script>
function sendEmail() {
document.getElementById('product_url_field').value = window.location.href
var emailpattern = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
var receivers_email = $("#receiver_email").val();
var sender_email = $("#sender_email_ID").val();
var sender_name = $("#senders_name").val();
var email_pathname = window.location.pathname;
var product_url = window.location.href;
if (receivers_email == '') {
$('#notify').removeClass().addClass("alert-danger");
$('#notification-text').empty().html("Invalid e-mail or fill the email address correctly");
$('#notification-text').show();
setTimeout(function() {
$('#notification-text').fadeOut('slow');
}, 10000);
return false;
}
else {
!emailpattern.test(receivers_email);
}
if(sender_name == ''){
$('#notify2').removeClass().addClass("alert-danger");
$('#notification-text2').empty().html("please fill the name");
$('#notification-text2').show();
setTimeout(function() {
$('#notification-text2').fadeOut('slow');
}, 10000);
return false;
}
if (sender_email == '') {
$('#notify1').removeClass().addClass("alert-danger");
$('#notification-text1').empty().html("Invalid e-mail or fill the email address correctly");
$('#notification-text1').show();
setTimeout(function() {
$('#notification-text1').fadeOut('slow');
}, 10000);
return false;
}
else {
!emailpattern.test(sender_email);
}
$('#notify3').removeClass().addClass("alert-success");
$('#sender_email').val('');
$('#notification-text3').empty().html("Email has sent successfully");
$('#notification-text3').show();
setTimeout(function() {
$('#notification-text3').fadeOut('slow');
}, 10000);
return true;
}
</script>
Controller php class:
public function tellaFriendEmail(){
if (isset($_POST['submit'])) {
$receiver_email = $_POST['receivers_email'];
$name = $_POST['sender_name'];
$email = $_POST['sender_email'];
$message = $_POST['tell_a_friend_message'];
$products_url = $_POST['product_url'];
$mail = new Mail();
$mail->protocol = $this->config->get('config_mail_protocol');
$mail->parameter = $this->config->get('config_mail_parameter');
$mail->smtp_hostname = $this->config->get('config_mail_smtp_hostname');
$mail->smtp_username = $this->config->get('config_mail_smtp_username');
$mail->smtp_password = html_entity_decode($this->config->get('config_mail_smtp_password'), ENT_QUOTES, 'UTF-8');
$mail->smtp_port = $this->config->get('config_mail_smtp_port');
$mail->smtp_timeout = $this->config->get('config_mail_smtp_timeout');
$mail->setTo($receiver_email);
$mail->setFrom($this->config->get('config_email'));
$mail->setSender("Waltersbay");
$mail->setSubject($name.' '.'wants you to checkout this product from waltersbay.com');
if ($message !=''){
$mail->setHtml('Hi Dear,<br/> please checkout the following product that'.' '.$name.' '.'wanted you to see.'.' '.'we hope that you will like it !!!!<br/>'.$products_url.'<br/>'.'<br/> Here is a little message from your friend:<br/>'.$message.'<br/>'.'<br/> Thank you, <br/> ');
}
else{
$mail->setHtml('Hi Dear,<br/> please checkout the following product that'.' '.$name.' '.'wanted you to see.'.' '.'we hope that you will like it !!!!<br/>'.$products_url.'<br/>'/*.'<br/> Here is a little message from your friend:<br/>'.$message.'<br/>'*/.'<br/> Thank you, <br/> ');
}
$mail->send();
}
else{
header('location : tella_friend.tpl');
}
}
}
Put a hidden input in your form. before submitting in your js, fill it with a new key according to time.
in your php file check if key is duplicate or not? or even if its filled?
Because js fill this input after clicking the submit button, every time you submit your form you have a new key! If you refresh the form, you're gonna send the previous value again.
For your problem then best practice recommended is to use jquery ajax requests.
Firstly if you pretend to use "submit" element then do following,
$(".form-vertical").submit(function(e) {
e.preventDefault();
//send ajax with your form data. Ample examples on SO already.
$.ajax(.....);
});
Other option we would recommend is to avoid using 'submit' behavior at first place for requirement you have.
1. Use button elements instead of submit element.
2. Attach click event on button. i.e. in your case 'send'.
3. On click, send ajax as described above. This will avoid doing things like onsubmit="return sendEmail();" you had to do.
4. Also following is not required as well,
$(".form-vertical").submit(function(e) {
e.preventDefault();
as it will be done as follows,
$("button#buttonId").click(function(e) {
// your ajax call.....
}

Using jQuery validate on select list

I have the following javascript:
var $step = $(".wizard-step:visible:last"); // get current step
var validator = $("#WizardForm").validate(); // obtain validator
var anyError = false;
$step.find("input").each(function ()
{
if (!validator.element(this)) { // validate every input element inside this step
anyError = true;
}
});
This is successfully validating all my input fields but upon trying to apply a similar method to the select type using code:
$step.find("select").each(function () {
if (!validator.element(this)) { // validate every input element inside this step
anyError = true;
}
});
My HTML is as follows:
<div class="wizard-step" id="step1" visibility="hidden" style="display: block;">
<div class="row">
<div class="col-md-6 column ui-sortable">
<div class="form-group">
<label class="control-label col-md-4" for="Tariff_Type">Tariff Type</label>
<div class="col-md-8">
<select style="width:100%;height:35px;border-radius:4px;padding-left:10px;" id="TariffType" name="TariffType" class="form-control input required">
<option value="">Please Select Tariff Type</option>
<option value="keypad account">Say Hello To Budget Extra Discount</option>
<option value="bill pay account">Standard 24H</option>
</select>
<span class="field-validation-valid text-danger" data-valmsg-for="TariffType" data-valmsg-replace="true"></span>
</div>
</div>
</div>
</div>
</div>
How can I ensure that a TariffType value is selected using this method?
Try the .valid() method instead...
if (! $(this).valid()) { ...

Validate div is not empty with jquery

I need to validate that both the text input, .search-results div within the "Current Images" fieldset and dropdown selection are all not empty. I have the logic for the text input and dropdown working, but can't figure out why the empty div logic is not working:
<div class="input-group col-md-6">
<input type="text" class="form-control" placeholder="Search by Asset ID" maxlength="64" class="form-control" id="imageid" name="imageid"> <span class="input-group-btn">
<button class="btn btn-default image-search" type="button">Search</button>
</span>
</div>
<fieldset class="scheduler-border">
<legend class="scheduler-border">Current Images</legend>
<div class="scheduler-broder">
<div class="search-results"></div>
</div>
</fieldset>
</div>
<div class="form-group">
<label for="image">Select Asset Type:</label>
<select id='crop' class="btn btn-default" data-toggle="dropdown">
<option value="default">Choose Type</option>
<option value="now">Now</option>
<option value="livefeeds">Live Feeds</option>
</select>
</div>
<div class="form-group">
<label for="imageid">Select an image</label>
<input type="file" name="file" class="btn btn-default form-control" id="file" accept="image/jpg, image/png, image/jpeg" />
</div>
function checkForInputs() {
var filledUp = $("#imageid").val() != '' && $("#crop").val() != "default" && $(".search-results").val() != '';
if (!filledUp) {
$("#file").attr("disabled", true);
} else if (filledUp) {
$("#file").attr("disabled", false);
}
}
$("#imageid").keyup(function () {
checkForInputs();
});
$("#crop").change(function () {
checkForInputs();
});
checkForInputs();
JSfiddle: link
Use $(".search-results").text() instead of $(".search-results").val()
Do the same for all the elements that don't belong to a form, like div, span, p, etc.
Take a look at the doc: http://api.jquery.com/val/
Method .val() as it described on jquery website:
Get the current value of the first element in the set of matched elements or set the value of every matched element.
You should use .text() instead of .val()
In this case your validation should be
var filledUp = $("#imageid").val() != '' && $("#crop").val() != "default" && $(".search-results").text() != '';
So this jsfiddle is working
you can use
if($('#mydiv').html().length() == 0)
{
//do something
}
this is for compare with empty value
other way to do this task is compare with function "children", example.
if($('.search-results').children.length == 0)
{
// dosomething
}
good luck !

Categories

Resources