Having some issue with show and hide. How to solve this? - javascript

My Form:
<form name="test" action="" method="post">
Day And Time Available:<br/>
<input type="checkbox" name="day[]" id="day1" value="monday" onclick="show();"/>Monday<br/>
<input type="checkbox" name="day[]" id="day2" value="Tuesday" onclick="show();"/>Tuesday<br/>
<input type="checkbox" name="day[]" id="day3" value="Wednesday" onclick="show();"/>Wednesday<br/>
<input type="checkbox" name="day[]" id="day4" value="Thursday" onclick="show();"/>Thursday<br/>
</form>
<p style="visibility:hidden" id="timing">Here I am maintain the form</p>
<input type="submit" name="submit" onclick="return valid();"/>
</form>
If user have have selected Monday, tuesday I want output like this:
Monday
From Time
<select name="Fromtime" id="Fromtime">
<option value="6Am">6Am</option>
<option value="7Am">7Am</option>
<option value="8Am">8Am</option>
</select>
To Time
<select name="Totime" id="Totime">
<option value="6Am">6Am</option>
<option value="7Am">7Am</option>
<option value="8Am">8Am</option>
</select>
Tuesday:
From Time
<select name="Fromtime" id="Fromtime">
<option value="6Am">6Am</option>
<option value="7Am">7Am</option>
<option value="8Am">8Am</option>
</select>
To Time
<select name="Totime" id="Totime">
<option value="6Am">6Am</option>
<option value="7Am">7Am</option>
<option value="8Am">8Am</option>
</select>
How do I solve this in jQuery. Based on user Selection I want to show the day and timing form.
Likewise if the user selects Monday, Tuesday and Wednesday how do I show the day and timing form
My JavaScript:
<script type="text/javascript">
function show()
{
var flag = 0;
for (var i = 1; i< 7; i++)
{
if(document.getElementById("day"+i).checked)
{
document.getElementById('Fromtime').style.visibility='visible';
document.getElementById('Totime').style.visibility='visible';
}
}
return true;
}
</script>

As #Jai mentions, there are a couple of issues with your HTML. First, you cannot have multiple elements with the same ID, e.g: your 'Fromtime' and 'Totime' select boxes.
All the data you wish to submit needs to be wrapped in <form> tags. It looks like you've got one too many closing tags here which will cause problems.
That being said, you can achieve the show/hide effect with something like the following (I've stayed away from jQuery for something this simple):
function show(element) {
var day = element.value; // gets the value of checkbox, e.g: 'monday'
var timeElement = document.querySelector('.times-' + day); // finds correct times- element for day
if (element.checked) {
timeElement.style.display = 'block';
} else {
timeElement.style.display = 'none';
}
}
.hidden {
display: none;
}
input[type=submit] {
margin-top: 10px;
}
<form name="test" action="" method="post">
<fieldset>
<legend>Day And Time Available:</legend>
<input type="checkbox" class="day" value="monday" onclick="show(this);"/>Monday<br/>
<input type="checkbox" class="day" value="tuesday" onclick="show(this);"/>Tuesday<br/>
</fieldset>
<div class="times-monday hidden">
<p>Monday</p>
<label for="FromtimeMonday">From Time</label>
<select name="FromtimeMonday" id="FromtimeMonday">
<option value="6Am">6Am</option>
<option value="7Am">7Am</option>
<option value="8Am">8Am</option>
</select>
<label for="TotimeMonday">To Time</label>
<select name="TotimeMonday" id="TotimeMonday">
<option value="6Am">6Am</option>
<option value="7Am">7Am</option>
<option value="8Am">8Am</option>
</select>
</div>
<div class="times-tuesday hidden">
<p>Tuesday</p>
<label for="FromtimeTueday">From Time</label>
<select name="FromtimeTueday" id="FromtimeTueday">
<option value="6Am">6Am</option>
<option value="7Am">7Am</option>
<option value="8Am">8Am</option>
</select>
<label for="TotimeTueday">To Time</label>
<select name="TotimeTueday" id="TotimeTueday">
<option value="6Am">6Am</option>
<option value="7Am">7Am</option>
<option value="8Am">8Am</option>
</select>
</div>
<input type="submit" name="submit" text="submit" />
</form>

Related

How to fix pricing on Clicking dropdown menu select-option and would change or update after clicking another option?

> *** Dropdown Select-option Vehicle Type ***
<div class="col-md-8 col-sm-8">
<h5><strong> Select <c style="color: #880707;">Vehicle</c></strong></h5>
<select id="name" required>
<option value="selectVehicle">----- Select Vehicle -----</option>
<optgroup label="Pick-Up">
<option value="Light_Truck" id="option_1">Light Truck</option>
</optgroup>
<optgroup label="Van">
<option value="Van" id="option_2">Van (Manual)</option>
</optgroup>
<optgroup label="7-Seaters">
<option value="Innova_AT" id="option_3">Innova (AT)</option>
<option value="Innova_MT" id="option_4">Innova (Manual)</option>
<option value="Xpander" id="option_5">Mitsubishi Expander</option>
<option value="Suzuki_XL7" id="option_6">Suzuki XL7</option>
</optgroup>
<optgroup label="Sedan">
<option value="Vios" id="option_7">Toyota Vios</option>
<option value="Ciaz" id="option_8">Suzuki Ciaz</option>
<option value="Mirage_G4" id="option_9">Mirage G4</option>
</optgroup>
<optgroup label="Hatchback">
<option value="Mirage_GLS" id="option_10">Mirage GLS</option>
<option value="Wigo" id="option_11">Toyota Wigo</option>
</optgroup>
</select>
</div>
> *** Days-Weeks-Months Rental Duration Input ***
<div class="col-md-12 col-sm-12">
<h5><strong> Rental <c style="color: #880707;">Duration</c></strong></h5>
<fieldsets>
<input class="col-md-4" type="text" id="days" name="Days" pattern="\d*" placeholder="Days*"/>
<input class="col-md-4" type="text" id="weeks" name="Weeks" pattern="\d*" placeholder="Weeks*"/>
<input class="col-md-4" type="text" id="months" name="Months" pattern="\d*" placeholder="Months*"/>
</fieldsets>
</div>
> *** Total Cost Output ***
<div class="col-md-6 col-sm-12">
<h5><strong> Total <c style="color: #880707;">Cost</c></strong><sup> negotiable*</sup></h5>
<fieldset name="Total">
<output id="cost"> $ 0.00</output>
</fieldset>
</div>
The script works fine, it would calculate when selecting vehicles then inputting duration of rental, but vise versa it wont calculate, it stays on $ 0.00.
<script>
const rates={
option_1:[350,2200,5400],
option_2:[380,2400,6000],
option_3:[300,1800,4500],
option_4:[250,1700,4200],
option_5:[280,1680,4510],
option_6:[250,1690,4250],
option_7:[180,1200,3000],
option_8:[180,1200,3000],
option_9:[180,1200,3000],
option_10:[160,980,2500],
option_11:[160,980,2500]};
const D=[], cost=document.getElementById("cost");
document.querySelector("fieldsets").querySelectorAll("input").forEach(e=>{D.push(e);e.addEventListener("input",calc)});
document.querySelectorAll("option").forEach(e=>{e.addEventListener("click",calc)});
function calc(ev){
const prod=document.querySelector("option:checked"),
r=prod?rates[prod.id]:[0,0,0];
cost.textContent='$ '+ r.reduce((a,c,i)=>a+c*(D[i].value??0),0).toFixed(2);
}
</script>
When inputting rental duration before selecting vehicle type it stays on $ 0.00 and vise versa works fine but after click other option the output stays as is.
it seems you're missing a check for the option id before running the calc, so i added an if statement to use before running the reduce function,
if(prod.id){ ... //reduce function }
you can now try the snippet
const rates={
option_1:[350,2200,5400],
option_2:[380,2400,6000],
option_3:[300,1800,4500],
option_4:[250,1700,4200],
option_5:[280,1680,4510],
option_6:[250,1690,4250],
option_7:[180,1200,3000],
option_8:[180,1200,3000],
option_9:[180,1200,3000],
option_10:[160,980,2500],
option_11:[160,980,2500]};
const D=[], cost=document.getElementById("cost");
document.querySelector("fieldsets").querySelectorAll("input").forEach(e=>{D.push(e);e.addEventListener("input",calc)});
document.querySelectorAll("option").forEach(e=>{e.addEventListener("click",calc)});
function calc(ev){
const prod=document.querySelector("option:checked"),
r=prod?rates[prod.id]:[0,0,0];
if(prod.id){
cost.textContent='₱ '+ r.reduce((a,c,i)=>a+c*(D[i].value??0),0).toFixed(2);
}
}
> *** Dropdown Select-option Vehicle Type ***
<div class="col-md-8 col-sm-8">
<h5><strong> Select <c style="color: #880707;">Vehicle</c></strong></h5>
<select id="name" required>
<option value="selectVehicle">----- Select Vehicle -----</option>
<optgroup label="Pick-Up">
<option value="Light_Truck" id="option_1">Light Truck</option>
</optgroup>
<optgroup label="Van">
<option value="Van" id="option_2">Van (Manual)</option>
</optgroup>
<optgroup label="7-Seaters">
<option value="Innova_AT" id="option_3">Innova (AT)</option>
<option value="Innova_MT" id="option_4">Innova (Manual)</option>
<option value="Xpander" id="option_5">Mitsubishi Expander</option>
<option value="Suzuki_XL7" id="option_6">Suzuki XL7</option>
</optgroup>
<optgroup label="Sedan">
<option value="Vios" id="option_7">Toyota Vios</option>
<option value="Ciaz" id="option_8">Suzuki Ciaz</option>
<option value="Mirage_G4" id="option_9">Mirage G4</option>
</optgroup>
<optgroup label="Hatchback">
<option value="Mirage_GLS" id="option_10">Mirage GLS</option>
<option value="Wigo" id="option_11">Toyota Wigo</option>
</optgroup>
</select>
</div>
> *** Days-Weeks-Months Rental Duration Input ***
<div class="col-md-12 col-sm-12">
<h5><strong> Rental <c style="color: #880707;">Duration</c></strong></h5>
<fieldsets>
<input class="col-md-4" type="text" id="days" name="Days" pattern="\d*" placeholder="Days*"/>
<input class="col-md-4" type="text" id="weeks" name="Weeks" pattern="\d*" placeholder="Weeks*"/>
<input class="col-md-4" type="text" id="months" name="Months" pattern="\d*" placeholder="Months*"/>
</fieldsets>
</div>
> *** Total Cost Output ***
<div class="col-md-6 col-sm-12">
<h5><strong> Total <c style="color: #880707;">Cost</c></strong><sup> negotiable*</sup></h5>
<fieldset name="Total">
<output id="cost"> ₱ 0.00</output>
</fieldset>
</div>

Calculate price selects to a textarea with a button

I want bring the value of the label "precio" in the selects, make the sum of this values and put into the textarea "cuenta" after click the button "añadir al pedido".
The label "value" of the selects it's saved in the textarea "pedido"
<script>window.jQuery || document.write('<script src="js/jquery-1.9.1.min.js"><\/script>')</script>
<script>
function calcular(){
var cuenta=0.00:
$('#pedido').val($('#pedido').val()+"\n"+$('#Pizzas option:selected').text());
var newPrice=cuenta;
var newPrice+=parseFloat($(this).find('#Pizzas option:selected').attr('precio'));
$('#pedido').val($('#pedido').val()+"\n"+$('#Bebidas option:selected').text());
var newPrice+=parseFloat($(this).find('#Bebidas option:selected').attr('precio'));
$("#cuenta").html(newPrice);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<select id="Pizzas" name="Pizzas" class="form-control" >
<?php
<option value="<?php echo $datos[0];?>" precio="<?php echo $datos[1];?>"><?php echo $datos[0];?></option>
<?php
}
?>
</select>
<select id="Bebidas" name="Bebidas" class="form-control" >
<?php
<option value="<?php echo $datos[0];?>" precio="<?php echo $datos[1];?>"><?php echo $datos[0];?></option>
<?php
}
?>
</select>
<div class="col-12">
<div style="padding-left:20px;">
<textarea name="pedido" class="form-control" id="pedido" cols="30" rows="10" placeholder="Pedido" ></textarea>
</div>
</div>
<div class="col-12 col-lg-6">
<div style="padding-left:10px;">
<input type="text" name="cuenta" id="cuenta" class="form-control" placeholder="Cuenta" required >
</div>
</div>
<button name="añadir" type="button" class="btn btn-primary p-3 px-xl-4 py-xl-3" onclick="calcular();"><span></span> Añadir al Pedido</button>
Check this out.
When you pick any item in select list the select element gets the value of the selected item. Also you shouldn't change textarea inner html, you have to change its value.
There is some nuance of how does js engine works.
+"123" it is the same as parseInt("123"). Event better because parseInt is going to drop the reminder, but +"12.3" return 12.3.
If you wrap your select lists in form you can add the require attribute to them and then check that any of items has been chosen.
let allOrdersTotalSumm = 0
let form = document.querySelector('#order-form')
let pizas = document.querySelector('#Pizzas')
let drinks = document.querySelector('#Drinks')
let priceArea = document.querySelector('#cuenta')
let selectedArea = document.querySelector('#pedido')
document.querySelector('#calc').addEventListener('click', calcTotalSum, false)
function calcTotalSum() {
// Check that items are picked
if (!form.reportValidity()) {
return false
}
let totalSum = +pizas.value + +pizas.value
let selectedPiza = pizas.options.item(pizas.options.selectedIndex)
let selectedDrink = drinks.options.item(drinks.options.selectedIndex)
selectedArea.value += `${selectedPiza.textContent} with ${selectedDrink.textContent}.Total: ${totalSum}\n`
allOrdersTotalSumm += totalSum
priceArea.value = allOrdersTotalSumm
// Reset lists to make a new order
form.reset()
}
<div style="margin-bottom:10px;">
<form id="order-form">
<select id="Pizzas" name="Pizzas" class="form-control" data-title="" required>
<option value="" selected>Please chose your pizza</option>
<option value="10">Cheesy pizzza</option>
<option value="12">Cheesy chizz pizzza</option>
<option value="15">Cheesy beacon cheees pizzza</option>
</select>
<select id="Drinks" name="Drinks" class="form-control" data-title="" required>
<option value="" selected>Please chose your drink</option>
<option value="7">Coke</option>
<option value="9">Pepsi</option>
<option value="12">Milkis</option>
</select>
</form>
</div>
<div style="margin-bottom:10px;">
<textarea name="pedido" class="form-control" id="pedido" cols="60" rows="10" placeholder="Pedido"></textarea>
</div>
<input type="text" name="cuenta" id="cuenta" class="form-control" placeholder="Cuenta" required>
<button id="calc" name="añadir" type="submit">Añadir al Pedido</button>
Based on your description, i think this is what you want.
Just tell me if i got wrong, and tell me if it's what you expected.
Hope it help.
function calcular() {
let total = parseInt($('#Pizzas').val()) + parseInt($('#Bebidas').val());
$('#cuenta').val(total);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<label>Select 1</label>
<select id="Pizzas" name="Pizzas" class="form-control" required>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
<br>
<label>Select 2</label>
<select id="Bebidas" name="Bebidas" class="form-control" required>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
</select>
<br><br>
<input type="text" name="cuenta" id="cuenta" class="form-control" placeholder="Cuenta" required>
<button name="añadir" type="button" class="btn btn-primary p-3 px-xl-4 py-xl-3" onclick="calcular();"><span></span> Añadir al Pedido</button>

Change the form action when an onchange event is triggered on <select> with 2 forms on page

I ran into an issue where I have two forms on a page -
A desktop version of the form
A mobile version.
Both forms don't show to the user as it depends on their viewport or device. When the user selects "Student Loan" from the agency drop-down selection (in either form), we want the form submission's action to be /quote/quotes-sl.php instead of the form default of /quote/quotes.php.
The good news is that on the mobile-friendly form (the first form in the code below), the solution works. However, for the desktop form, it does not even though it has the same form id/name. I tried renaming the desktop form to have a different formID/name` and then add another script for that form, but that doesn't work.
Any direction or advice is greatly appreciated.
(function() {
var theForm = document.getElementById('tdhcustom-pre-1-form');
var theSelector = document.getElementById('agency');
theSelector.onchange = function() {
theForm.action = theSelector[theSelector.selectedIndex].getAttribute('data-action');
}
})();
<form id="tdhcustom-pre-1-form" accept-charset="UTF-8" action="/quote/quotes.php" method="post" name="tdhcustom-pre-1-form">
<div>
<input id="edit-lead-source-description" name="lead_source_description" type="hidden" value="1.test" />
<div id="edit-owed-wrapper" class="form-item">
<label class="edit-owed" for="edit-owed"> Tax Debt Owed: <span class="form-required" title="This field is required.">*</span></label>
<select id="edit-owed" class="form-select required" name="owed">
<option selected="selected" value="">Select...</option>
<option value="$30,000 to $39,999">$30,000 to $39,999</option>
<option value="$40,000 to $59,999">$40,000 to $59,999</option>
<option value="$60,000 to $79,999">$60,000 to $79,999</option>
<option value="$80,000 to $99,999">$80,000 to $99,999</option>
<option value="$100,000+">$100,000 +</option>
</select>
</div>
<div id="edit-agency-wrapper" class="form-item">
<label class="edit-agency" for="edit-agency"> Tax Agency: <span class="form-required" title="This field is required.">*</span></label>
<select id="agency" class="form-select required" name="agency">
<option selected="selected" value="">Select Agency...</option>
<option value="Student Loan" data-action="/quote/quotes-sl.php">Student Loan</option>
<option value="Federal" data-action="/quote/quotes.php">Federal</option>
<option value="STATE" data-action="/quote/quotes.php">State</option>
<option value="FEDERAL_AND_STATE" data-action="/quote/quotes.php">Federal and State</option>
</select>
</div>
<input id="edit-submit" class="form-submit" height="31" name="submit" src="http://www.test.com/wp-content/uploads/2009/07/form-submit-6-17-small.png" type="image" value="Submit" width="214" />
<input id="form-5ezy7kqpVIYFiVUgKIyxbp4n6MQ7ZqHuo33GJbq0QZE" name="form_build_id" type="hidden" value="form-5ezy7kqpVIYFiVUgKIyxbp4n6MQ7ZqHuo33GJbq0QZE" />
<input id="edit-tdhcustom-pre-1-form" name="form_id" type="hidden" value="tdhcustom_pre_1_form" />
</div>
</form>
<div class="mycustombanner desk-view">
<img class="wp-image-12546 size-full alignnone" src="http://www.test.com/wp-content/uploads/2009/12/top-form-irs-hardship-status.png" alt="irs hardship status" width="618" height="194" />
<form id="tdhcustom-pre-1-form" accept-charset="UTF-8" action="/quote/quotes.php" method="post" name="tdhcustom-pre-2-form">
<div>
<input id="edit-lead-source-description" name="lead_source_description" type="hidden" value="1.test-desktop" />
<div id="edit-owed-wrapper" class="form-item">
<label for="edit-owed"> Tax Debt Owed: <span class="form-required" title="This field is required.">*</span></label>
<select id="edit-owed" class="form-select required" name="owed">
<option selected="selected" value="">Select...</option>
<option value="$30,000 to $39,999">$30,000 to $39,999</option>
<option value="$40,000 to $59,999">$40,000 to $59,999</option>
<option value="$60,000 to $79,999">$60,000 to $79,999</option>
<option value="$80,000 to $99,999">$80,000 to $99,999</option>
<option value="$100,000+">$100,000 +</option>
</select>
</div>
<div id="edit-agency-wrapper" class="form-item">
<label for="edit-agency"> Tax Agency: <span class="form-required" title="This field is required.">*</span></label>
<select id="agency" class="form-select required" name="agency">
<option selected="selected" value="">Select Agency...</option>
<option value="Student Loan" data-action="/quote/quotes-sl.php">Student Loan</option>
<option value="Federal" data-action="/quote/quotes.php">Federal</option>
<option value="STATE" data-action="/quote/quotes.php">State</option>
<option value="FEDERAL_AND_STATE" data-action="/quote/quotes.php">Federal and State</option>
</select>
</div>
<input id="edit-submit" class="form-submit" height="37" name="submit" src="http://www.test.com/wp-content/uploads/2010/04/form-submit-6-17-1.png" type="image" value="Submit" width="207" />
<input id="form-5ezy7kqpVIYFiVUgKIyxbp4n6MQ7ZqHuo33GJbq0QZE" name="form_build_id" type="hidden" value="form-5ezy7kqpVIYFiVUgKIyxbp4n6MQ7ZqHuo33GJbq0QZE" />
<input id="edit-tdhcustom-pre-1-form" name="form_id" type="hidden" value="tdhcustom_pre_1_form" />
</form>
</div>
It is invalid HTML to have more than one element with the same ID in one document - that's why the selector is failing.
Try giving both forms different IDs, as well as for the select element, for example:
<form id="tdhcustom-pre-1-form1"...
<select id="agency1"...
...
...
<form id="tdhcustom-pre-1-form2"...
<select id="agency2"...
Then you could do:
[
['tdhcustom-pre-1-form1', 'agency1'],
['tdhcustom-pre-1-form2', 'agency2'],
].forEach(([formSelector, agencySelector]) => {
const form = document.getElementById(formSelector);
const agency = document.getElementById(agencySelector);
agency.addEventListener('change', () => {
form.action = agency[agency.selectedIndex].getAttribute('data-action');
});
});
Now that I've looked at your code more, I'm going to say more confidently that sharing the same id between your forms is the problem you're having. This line:
var theForm = document.getElementById('tdhcustom-pre-1-form');
...isn't going to care which form is hidden, and which form is shown. It's always going to return you the same form. Your browser must be favoring the mobile form over the desktop form.

how to change the label text present inside a div? and how to change the dropdown to a textbox?

i am having the following html
<div class="field">
<label for="approval_approvers_attributes_0_approver_type">Approver</label>
<select class="form-control appr_type" id="approval_approvers_attributes_0_approver_type" name="approval[approvers_attributes][0][approver_type]" onchange="$.fn.myFunc(this);">
<option selected="selected" value="Role">Role</option>
<option value="Specific User">Specific User</option>
</select>
</br>
</br>
</div>
<div class="field" class="role">
<label for="approval_approvers_attributes_0_approver_value">Role</label>
<select class="form-control appr_type" id="approval_approvers_attributes_0_approver_value" name="approval[approvers_attributes][0][approver_value]">
<option value="hr manager">hr manager</option>
<option selected="selected" value="reporting manager">reporting manager</option>
</select>
<input id="approval_approvers_attributes_0__destroy" name="approval[approvers_attributes][0][_destroy]" type="hidden" value="false" /><a class=" remove_nested_fields" data-association="approvers" href="javascript:void(0)">Remove</a>
</br>
</br>
</div>
and the followng js function definition:
$.fn.myFunc = function (button) {
var id = $(button).attr('id');
id = button.id;
$(button).next().label.text("specific user");
}
the call to this above Jquery function is made in the first div. this function is called when the dropdown in the first div is changed. in this function i want the label text to be changed to "specific user" which is present in the second div, when the user selects "specific user". and accordingly i want to change the dropdown which is present in the second div to textbox, to enter the specific user name. how can i do that?
You need to change your code like,
<div class="field" class="role">
<label for="approval_approvers_attributes_0_approver_value">Role</label>
<select class="form-control appr_type" id="approval_approvers_attributes_0_approver_value" name="approval[approvers_attributes][0][approver_value]">
<option value="hr manager">hr manager</option>
<option selected="selected" value="reporting manager">reporting manager</option>
</select>
<input type="text" class="inpt_specific_user" style="display:none"/>
<input id="approval_approvers_attributes_0__destroy" name="approval[approvers_attributes][0][_destroy]" type="hidden" value="false" /><a class=" remove_nested_fields" data-association="approvers" href="javascript:void(0)">Remove</a>
</br>
</br>
</div>
<script>
$.fn.myFunc = function (button) {
var id = $(button).attr('id');
id = button.id;
var $nextDiv = $(button).closest('div.field') // get closest parent field
.next('div.field') // get next parent field
$nextDiv.find('label') // find label
.text(button.value); //change text, this.value so that it will be dynamic for both the values
$nextDiv.find('select.appr_type,input.inpt_specific_user')
.toggle(); // toggle select/input =>hide/show
}
</script>
$.fn.myFunc = function(button) {
var id = $(button).attr('id');
id = button.id;
var $nextDiv = $(button).closest('div.field') // get closest parent field
.next('div.field') // get next parent field
$nextDiv.find('label') // find label
.text(button.value); //change text, this.value so that it will be dynamic for both the values
$nextDiv.find('select.appr_type,input.inpt_specific_user')
.toggle(); // toggle select/input =>hide/show
}
$('#approval_approvers_attributes_0_approver_type').on('change', function() {
$.fn.myFunc(this);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="field">
<label for="approval_approvers_attributes_0_approver_type">Approver</label>
<select class="form-control appr_type" id="approval_approvers_attributes_0_approver_type" name="approval[approvers_attributes][0][approver_type]" onchange="">
<option selected="selected" value="Role">Role</option>
<option value="Specific User">Specific User</option>
</select>
</br>
</br>
</div>
<div class="field" class="role">
<label for="approval_approvers_attributes_0_approver_value">Role</label>
<select class="form-control appr_type" id="approval_approvers_attributes_0_approver_value" name="approval[approvers_attributes][0][approver_value]">
<option value="hr manager">hr manager</option>
<option selected="selected" value="reporting manager">reporting manager</option>
</select>
<input type="text" class="inpt_specific_user" style="display:none" />
<input id="approval_approvers_attributes_0__destroy" name="approval[approvers_attributes][0][_destroy]" type="hidden" value="false" /><a class=" remove_nested_fields" data-association="approvers" href="javascript:void(0)">Remove</a>
</br>
</br>
</div>
Updated, code without using extra element and using replaceWith()
$.fn.myFunc = function(button) {
var id = $(button).attr('id');
id = button.id;
var $nextDiv = $(button).closest('div.field') // get closest parent field
.next('div.field') // get next parent field
$nextDiv.find('label') // find label
.text(button.value); //change text, this.value so that it will be dynamic for both the values
var $el = null;
if (button.value != 'Role') {
$nextDiv.find('select.appr_type').replaceWith('<input type="text" class="form-control appr_type" id="approval_approvers_attributes_0_approver_value" name="approval[approvers_attributes][0][approver_value]" />');
} else {
$nextDiv.find('input.appr_type').replaceWith('<select class="form-control appr_type" id="approval_approvers_attributes_0_approver_value" name="approval[approvers_attributes][0][approver_value]">\
<option value="hr manager">hr manager</option>\
<option selected="selected" value="reporting manager">reporting manager</option>\
</select>');
}
}
$('#approval_approvers_attributes_0_approver_type').on('change', function() {
$.fn.myFunc(this);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="field">
<label for="approval_approvers_attributes_0_approver_type">Approver</label>
<select class="form-control appr_type" id="approval_approvers_attributes_0_approver_type" name="approval[approvers_attributes][0][approver_type]" onchange="">
<option selected="selected" value="Role">Role</option>
<option value="Specific User">Specific User</option>
</select>
</br>
</br>
</div>
<div class="field" class="role">
<label for="approval_approvers_attributes_0_approver_value">Role</label>
<select class="form-control appr_type" id="approval_approvers_attributes_0_approver_value" name="approval[approvers_attributes][0][approver_value]">
<option value="hr manager">hr manager</option>
<option selected="selected" value="reporting manager">reporting manager</option>
</select>
<input id="approval_approvers_attributes_0__destroy" name="approval[approvers_attributes][0][_destroy]" type="hidden" value="false" /><a class=" remove_nested_fields" data-association="approvers" href="javascript:void(0)">Remove</a>
</br>
</br>
</div>

Better way to change id's of controls using jquery

I have the following form that renders from a django model_formset. It starts with one form and some static controls (like date etc).The form set fields are inside the 'form-wrapper' div
<form action="/customer/images/1/upload_xray" method="post" id="xrayform" enctype="multipart/form-data">
<input id="id_form-TOTAL_FORMS" name="form-TOTAL_FORMS" type="hidden" value="1"><input id="id_form-INITIAL_FORMS" name="form-INITIAL_FORMS" type="hidden" value="0"><input id="id_form-MAX_NUM_FORMS" name="form-MAX_NUM_FORMS" type="hidden" value="1000">
<input type="hidden" name="csrfmiddlewaretoken" value="LI1L39J1C7P4tQeqfJhL5CBuW283FmOI">
<div class="form-group">
<label for="date">Date</label>
<input id="date" type="text" name="date" class="form-control input-sm datepicker input-append date" readonly="">
</div>
<div class="form-group">
<label for="id_title">Title</label>
<select class="form-control input-sm" id="id_title" name="title">
<option value="" selected="selected">---------</option>
<option value="Observation">Observation</option>
<option value="Initial">Initial</option>
<option value="Progress">Progress</option>
<option value="Final">Final</option>
<option value="Post Treatment">Post Treatment</option>
</select>
</div>
<hr class="divider">
<div class="form-wrapper">
<div class="form-group">
<label for="id_form-0-image">Image</label>
<input id="id_form-0-image" name="form-0-image" type="file">
</div>
<div class="form-group">
<label for="id_form-0-type">Type</label>
<select class="form-control input-sm" id="id_form-0-type" name="type">
<option value="" selected="selected">---------</option>
<option value="xray">X-ray Image</option>
<option value="internal">Intraoral Image</option>
<option value="external">Extra-oral Image</option>
<option value="model">Model</option>
</select>
</div>
<div class="form-group">
<label for="id_form-0-desc">Desc</label>
<select class="form-control input-sm" id="id_form-0-desc" name="form-0-desc">
<option value="" selected="selected">---------</option>
<optgroup label="Xray" />
<option value="PA Ceph">PA Ceph</option>
<option value="Lateral Ceph">Lateral Ceph</option>
<option value="Panoramic">Panoramic</option>
<optgroup label="Interior oral">
<option value="Anterior Occlution">Anterior Occlution</option>
<option value="Anterior Occlusion Relaxed">Anterior Occlusion Relaxed</option>
<option value="Overjet Right">Overjet Right</option>
<option value="Overjet Left">Overjet Left</option>
<option value="Right Occlusion">Right Occlusion</option>
<option value="Left Occlusion">Left Occlusion</option>
<option value="Upper Occlusal">Upper Occlusal</option>
<option value="Lower Occlusal">Lower Occlusal</option>
<optgroup label="External oral" />
<option value="Frontal">Frontal</option>
<option value="Lateral Right">Lateral Right</option>
<option value="Lateral Left">Lateral Left</option>
<option value="Oblique smile Right">Oblique smile Right</option>
<option value="Oblique smile Left">Oblique smile Left</option>
<option value="Frontal smile">Frontal smile</option>
<option value="Oblique Right">Oblique Right</option>
<option value="Oblique Left">Oblique Left</option>
<optgroup label="Model"/>
<option value="Model Upper Occlusal">Model Upper Occlusal</option>
<option value="Model Lower Occlusal">Model Lower Occlusal</option>
<option value="Model Right Buccal">Model Right Buccal</option>
<option value="Model Left Buccal">Model Left Buccal</option>
<option value="Model Anterior Dental">Model Anterior Dental</option>
</select>
</div>
</div>
</form>
<div class="row">
<button class="btn btn-sm btn-success pull-right" id="add-form">+</button>
</div>
The add button adds a new form-wrapper element and increments by one the proper input fields so the model_formset of django to function correctly. Each new form-wrapper element consists of a delete button to delete it. On deletion javascript corrects the id's and values again for the formset to function correctly. I have made it work, but uses to much .each methods. Do u think is a better way to do that?
javascript
$(document).on('click','.delete', function (e){
e.preventDefault();
var forms;
var index = parseInt($(this).prop('id')) - 1;
var formWrapper = $(".form-wrapper")[index];
formWrapper.remove();
forms = $(".form-wrapper");
$("#id_form-TOTAL_FORMS").val(parseInt($("#id_form-TOTAL_FORMS").val()) - 1);
forms = $('.form-wrapper');
forms.each(function (index, item){
var form_groups = $(item).children('.form-group');
form_groups.each(function (index2, item2){
controls = $(item2).children();
controls.each(function(index3, item3){
var id = $(item3).prop('id');
parts = id.split('-');
parts[1] = String(index);
id = parts.join('-');
});
});
});
$('button.delete').each(function(index, item){
var id = parseInt($(item).prop('id'));
id = index + 2; //First start button starts with id=2 as in "delete 2nd form"
console.log('id after '+id);
$(item).prop('id', id);
});
});
Basicaly take the formwrappers to know how many forms are there, take each children (form-group) and then each children(control elements) and change their id's. Not having any trouble in speed yet, it works great, but don't like it's cleanness.
You can use .attr() like
$('button.delete').attr('id', function (index, item) {
return index + 2;
});
Demo: Fiddle

Categories

Resources