Change value in div on changing drop down using jquery - javascript

I need to change value on a div according to selection in drop down box - tried this code but script does not seem to work
HTML dropdown list:
<form action="https://ccart.com/cart" method="post">
<input type="hidden" name="name" value="T-shirt" />
<input type="hidden" name="price" value="54" />
<select name="size" id="Field">
<option value="1{p-50}">Small</option>
<option value="2{p-24}">Medium</option>
<option value="3">Large</option>
</select>
<input type="submit" value="Lets go" class="cart"/>
</form>
<div id="1" class="box">4</div>
<div id="2" class="box">30</div>
<div id="3" class="box">54</div>
I tried using:
$(document).ready(function () {
$('.box').hide();
$('#1').show();
$('#Field').change(function () {
$('.box').hide();
$('#' + $(this).val()).show();
});
});
Jquery called:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js" type="text/javascript" charset="utf-8"></script>
Dropdown working fine but cannot get to show div.
Working fine now but problems changing id from numeric to string as recommended
<option value="Small{p-50}">Small</option>
<option value="Medium{p-24}">Medium</option>
<option value="Large">Large</option>
<div id="Small" class="box">4</div>
<div id="Medium" class="box">30</div>
<div id="Large" class="box">54</div>
Code:
$('.box').hide();
$('#Small').show();
$('#Field').change(function () {
$('.box').hide();
$('#' + parseInt($(this).val())).show();
});
If i leave original id values of 1,2 etc it works perfect

It's failing because of this:
<option value="1{p-50}">Small</option>
<option value="2{p-24}">Medium</option>
Because none of your divs have an ID attribute of #1{p-50} it won't be shown.
Unless the {p-50} or {p-24} are used for anything, just change them to this:
<option value="1">Small</option>
<option value="2">Medium</option>
JSFiddle
Also, as Sarfraz Mentioned, your IDs should also not be a number alone.

Well values of the dropdown items doesn't match ID's of your divs. If you really want to use them anyway you should use parseInt:
$('.box').hide();
$('#1').show();
$('#Field').change(function () {
$('.box').hide();
$('#' + parseInt($(this).val())).show();
});
parseInt will parse 1{p-50} to 1 and everything will work.
Note: since numeric ids is not valid in HTML4 you should make sure your define HTML5 doctype which is more tolerant about numbers as identifiers.

Related

How to elegantly add and remove elements from DOM

So I have a dynamic form where certain inputs should only become available (and visible) based upon what a user has already entered. The way I'm starting to go about it has a wrong smell.
It is straightforward enough to add material to the DOM
<script>
function addStuffToTheDOM(s1, s2){
var s1 = document.getElementById(s1);
var s2 = document.getElementById(s2);
s2.innerHTML = "";
if (s1.value==="job_1"){
s2.insertAdjacentHTML('afterend', '<p><select name="scholarship" id="scholarship"><option value="" disabled="disabled" selected="selected">*Position</option> <option value="" disabled="disabled" > </option> <option value="HR">HR</option> <option value="CTO">CTO</option> <option value="test">test</option> <option value="test2">test2</option> <option value="test3">test3</option> <option value="test4">test4</option> </select> </p> <select name="previous_experience" class="hidden"
id="new_to_demo"><option value="0" disabled="disabled" selected="selected"></option> <p> <p> <input type="text" name="supervisor" id="supervisor" maxlength="50" size="30"> <label for="supervisor">*Supervisor</label> </p> <p> <input type="text" name="office_location" id="office_location" maxlength="50" size="30"> <label for="office_location">Office location</label> </p> <p> <input type="text" name="programme_start_date" id="programme_start_date" maxlength="50" size="30"> <label for="programme_start_date">programme_start_date</label> </p>');
}
}
</script>
<!-- .... -->
<form>
<!-- ... -->
<select name="type" id="type" onchange="addStuffToTheDOM(this.id, 'alma_mater')">
<option value="" disabled="disabled" selected="selected">*Job Interest?</option>
<option value="" disabled="disabled" > </option>
<option value="job_1">The really big job</option>
<option value="job_2">The other job</option>
</select>
And while this insertion in itself could be better (instead of jamming an enormous string into insertAdjacentHTML() ) an immediate problem presents itself in that
If the user has made a mistake and selects the other option (for which all that inserted HTML is irrelevant) then some other code will have to be run to remove all those new elements. Yuck.
Without this removal process if the user selects the other option and then goes back and selects option "job_1" again, then the form is immediately broken by the duplication of all that content. Yikes.
The backend checking has to be extra careful to do proper checking: are inputs empty because they haven't been filled in, or because they simply don't exist?
What would be the ideal methodology for implementing this dynamic content?
Yes, that has a worrying smell. You could create a check-function that runs each time someone clicks/types (depending on what you want to include in your form) a field. That functions itself needs certain conditions that are going to be checked.
This is a quick example I put together. Use jQuery (or regular javascript if you want) and put together something like this. Hope this helps!
$(document).ready(function(){
$('#checkbox').click(function(){
if($("#checkbox").is(':checked'))
$("#textbox").hide();
else
$("#textbox").show();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<form>
<input id="checkbox" type="checkbox">I want to hide a textbox</input><br>
<input id="textbox" type="textbox" placeholder="This can be hidden"></input>
</form>
EDIT: To add, if you want to check for textbox values or textareas, in jQuery you use for example:
$('#textbox').val();

How to get dropdown value and show in textbox using jquery?

What I want to do is get data from drop down and pass the data to textbox
here is my dropdown and textbox code
<select name="criteria_title" id="chosen_a" data-placeholder="Select Category" class="chzn_z span3 dropDownId chzn-done" style="display: none;">
<option value=""></option>
<option value="1" data-id="10">a</option>
<option value="2" data-id="20">b</option>
<option value="3" data-id="30">c</option>
<option value="4" data-id="40">d</option>
<option value="5" data-id="50">e</option>
</select>
<div class=" control-group formSep template">
<label for="input01" class="control-label">Category Rate*:</label>
<div class="controls">
<input id="title" name="criteria_rate" size="30" type="text" class="criteria_rate span2" value="" readonly="readonly" />
</div>
</div>
here is how to get data-id from dropdown
var criteria_id = $(this).attr('data-id');
here is how to pass data to textbox
$('.criteria_rate').val(criteria_id);
here is my dropdown screenshot
Any idea how to solve my problem?
Here is what you need (I think)
FIDDLE
$('#chosen_a').change(function() {
$('#title').val($('#chosen_a option:selected').data('id'));
})
This is the most simple way
$(document).ready(function () {
$("#chosen_a").change(function () {
$('#title').val($("#chosen_a").val());
});
});
Try this:-
$('#chosen_a').change(function(){
//get the selected option's data-id value using jquery `.data()`
var criteria_rate = $(':selected',this).data('id');
//populate the rate.
$('.criteria_rate').val(criteria_rate);
});
Fiddle
Refer .data()
Here is a possible solution, uses jquery but get the data through the event data instead of using jquery.data (notice that it is a few characters shorter doing it this way :P )
$("#chosen_a").on("change", function (evt) {
$("#title").val(evt.target.selectedOptions[0].dataset.id);
});
Demonstrated on jsfiddle
(gave an alternative as I misread the question initially, so now I'm a little late with my correction)

jquery show and hide divs

I have a form with a yes|no question displayed by radio selectors. I have two divs each one containing different drop downs based on the yes|no response. I cannot figure out how to show one and hide the other.
jsFiddle of this code
$(document).ready(function(){
$("input[name=radio_button]").change(function() {
var test1= $(this).val();
$("#"+test1).show();
$("div.test2").hide();
});
$("input[name=radio_button]").select(function() {
var test2= $(this).val();
$("#"+test2).show();
$("div.test1").hide();
});
});
<p>
<label class="required"> </label>
Yes <input name="radio_button" id="radio_button" type="radio" value="test2" onChange="" />
No <input name="radio_button" id="radio_button" type="radio" value="test1" />
</p>
<p>
<label class="required">Device: </label><br />
<div id="test1" class="test1_div">
<label style="font-weight:600;">test1</label>
<select name="order.item" id="item" >
<option value="default">Please Select item</option>
</select>
</div>
<div id="test2" class="test2_div">
<label style="font-weight:600;">item2</label>
<select name="order.item" id="device">
<option value="default">Please Select Device</option>
</select>
</div>
</p>
To make one hidden and other visible , you have to first hide both the blocks then add show() on the block you want to see. This will work for you.
Assuming your markup (html) is correct, try the following. It binds to click-events of those radio buttons (both of them), always hides both divs first, and then shows the appropiate div only (the one that belongs to the radio button clicked).
$(document).ready(function(){
$("input[name=radio_button]").click(function() {
var test= $(this).val();
$("div.test1, div.test2").hide(); //Hide both divs
$("#"+test).show();
});
});

Find ID of a selectmenu

How can I get the name of the select tag?
I have several select menus. I can retrieve the submitted options. However, I would like to get the name, or even better, the ID of the select tag that holds the options.
Sample HTML:
<div id="prodAttributes_2">
<form id="attributesubmit">
<div data-role="fieldcontain">
<fieldset data-role="controlgroup">
<div role="heading" >Options:</div>
<select name="Memory" id="4">
<option value="3">16 mb</option>
<option value="4">32 mb</option>
</select>
<select name="Model" id="3">
<option value="6">Premium</option>
<option value="7">Deluxe</option>
</select>
</fieldset>
</div>
<input type="button" id="submitme" value="send" />
</form>
</div>
Solved Fiddle: JSFiddle
Add
var name = $(this).attr("name");
to your $('select').each call: http://jsfiddle.net/xPGUE/
You can use this.id within the each().
Note you can get the name with $(this).attr('name')
I've forked your jsfiddle
in your fiddle, where you get the alert
alert('Value: ' + selectedOption.val() + ' Text: ' + selectedOption.text());
you can access to the name or id of the option using
selectedOption.attr('name')
selectedOption.attr('id')
Try this:
$('select').each(function() {
alert($(this).attr('name'));
});

Show (Visible/Hidden NOT Show/Hide) HTML Element based on form select box selection

The following worked perfectly for my needs. Took the state of a checkbox and did wonderful things for me; Made 3 different form elements visible (vs. show/hide) based on checkbox checked or not checked. Simple, I guess. Then again, I base "simple" on how symmetrical the code looks and if it's less that 10 lines. Other than that, I'm lost. However, I've officially given up on messing around with IE's checkbox border issue and X-browser alignment yippeedoodles. I want pixel perfect the hard way. But I lost that battle. But rather than get into any discussion about that, I need to accomplish the same thing using a form select box as I was able to do with the checkboxes (below):
<form id="form">
<input id="checkbox" name="checkbox" type="checkbox" onclick="showhideid" />
</form>
#IdOne, #IdTwo, #IdThree (visibility:hidden;}
function showhideid()
{
if (document.form.checkbox.checked)
{
document.getElementById("IdOne").style.visibility = "visible";
document.getElementById("IdTwo").style.visibility = "visible";
document.getElementById("IdThree").style.visibility = "visible";
document.getElementById("IdFour").setAttribute("class", "required");
}
else
{
document.getElementById("IdOne").style.visibility = "hidden";
document.getElementById("IdTwo").style.visibility = "hidden";
document.getElementById("IdThree").style.visibility = "hidden";
document.getElementById("IdFour").setAttribute("class", "");
}
}
Now, if I can accomplish the same thing using a select box (below), I will die a happy man.
This is as far as I've gotten. I'm super dizzy from reading Jquery/CSS man pages and I just can't put it all together.
<html>
<form id="form">
<select name="SelectBox">
<option>Make a Choice</option>
<option value="Value1">Selection1</option>
<option value="Value2">Selection2</option>
<option value="Value3">Selection3</option>
</select>
<label id="IdOne" for="input1">MeAndMyInputAreInvisibleByDesign</label>
<input id="IdTwo" name="input1" type="text">
<span id="IdThree">Im Not In display:none Mode I'm In visibility:hidden Mode. Big difference."
</span>
<input id="IdFour" name="input2" type="text" class="I have none, but I will soon. I hope" />
</form>
</html>
take a look at the select tag:
<select name="SelectBox">
<option>Make a Choice</option>
<option value="IdTwo">Selection1</option> <!-- the value should be the id of the input field -->
<option value="IdThree">Selection2</option>
<option value="IdFour">Selection3</option>
</select>
Now you must give a selector class to each element you want to show/hide:
<input id="IdTwo" name="input1" type="text" class="toggle">
<span id="IdThree" class="toggle">
Im Not In display:none Mode I'm In visibility:hidden Mode. Big difference."
</span>
<input id="IdFour" name="input2" type="text" class="toggle" />
Now look at the javascript:
jQuery(document).ready(function(){
jQuery('input[name="SelectBox"]').change(function(){
jQuery('.toggle').css({"visibility":"hidden"});//Hide all
jQuery("#" + jQuery(this).val()).css({"visibility":"visible"});
});
});
You can do something like this:
<html>
<form id="form">
<input type="text" id="IdOne" class="toggle" />
<input type="text" id="IdTwo" class="toggle" />
<input type="text" id="IdThree" class="toggle" />
<select name="SelectBox" id="selectBox">
<option value="0">Make a Choice</option>
<option value="IdOne">First element</option>
<option value="IdTwo">Second element</option>
<option value="IdThree">Third element</option>
</select>
</html>
this in javascript:
jQuery(document).ready(function(){
jQuery("#selectBox").change(function(){
jQuery(".toggle").hide();
jQuery("#" + jQuery(this).val()).show();
});
});

Categories

Resources