Using Javascript function variables to define a DOM element - javascript

I'm using a yes/no dropdownbox to hide conditional form elements via CSS. It works fine if I manually define the form name and element name, but if I try to define them via variables it won't function. I've been troubleshooting and researching for about an hour to no avail. Here is my Javascript function.
function binaryHideShow(formName, elementName)
{
if (document.forms["'" + formName + "'"].elementName.value == "yes")
{
document.getElementById("'" + elementName + "'").setAttribute("class","show");
}
else
{
document.getElementById("'" + elementName + "'").setAttribute("class","hide");
}
}
And here is the HTML element.
<select name="PrimaryFiledBankruptcyDropDownList" onchange="binaryHideShow(this.form.name, this.attributes['name'].value);">
<option value=""></option>
<option value="yes">Yes</option>
<option value="no">No</option>
</select>
<div id="PrimaryFiledBankruptcyDropDownList">
<label for="PrimaryBankruptcyTypeDropDownList">Bankruptcy Type:</label>
<select name="PrimaryBankruptcyTypeDropDownList" onchange="">
<option value=""></option>
<option value="chapter-7">Chapter 7</option>
<option value="chapter-13">Chapter 13</option>
</select>
</div>
I've already ensured that my this statements on the html side are pulling the correct elements.
To be clear if I manually enter the variables names as per the example below it will work fine, and the html this statements return the EXACT names that I'm using below.
function binaryHideShow()
{
if (document.forms["ProgramApplicationForm"].PrimaryFiledBankruptcyDropDownList.value == "yes")
{
document.getElementById("PrimaryFiledBankruptcyDropDownList").setAttribute("class","show");
}
else
{
document.getElementById("PrimaryFiledBankruptcyDropDownList").setAttribute("class","hide");
}
}

There is an error in your function for access the element in your form, try:
function binaryHideShow(formName, elementName)
{
if (document.forms[formName][elementName].value == "yes")
{
document.getElementById(elementName).setAttribute("class","show");
}
else
{
document.getElementById(elementName).setAttribute("class","hide");
}
}

Change from
document.forms["'" + formName + "'"]
to
document.forms[ formName ]
Otherwise you're passing in a name as if you did "'PrimaryBankruptcyTypeDropDownList'" (note the double quotes).

This should get you started.
HTML
<form name="MyForm" id="MyForm">
<select name="PrimaryFiledBankruptcyDropDownList"nchange="binaryHideShow(this,this.form);">
<option value=""></option>
<option value="yes">Yes</option>
<option value="no">No</option>
</select>
</form>
JavaScript
function binaryHideShow(element,form) {
console.log("Element Name: " + element.name);
console.log("Form Name: " + form.name);
if(element.value == "yes") {
console.log('sure does');
} else {
console.log('nope');
}
}
Off topic - but, you might find this useful...
Look into separating your actions from your view - meaning: get rid of the "onchange" event and if possible - think about using jQuery.
Some good reads for you:
http://coding.smashingmagazine.com/2008/09/16/jquery-examples-and-best-practices/
https://developers.google.com/speed/docs/best-practices/rules_intro
jQuery pitfalls to avoid
http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#tip2
http://net.tutsplus.com/tutorials/javascript-ajax/14-helpful-jquery-tricks-notes-and-best-practices/

I ended up figuring it out. In order to use the element portion of the document.forms you have to specify elements[] with the variables inside as such:
function binaryHideShow(formName, elementName)
{
if (document.forms[formName].elements[elementName].value == "yes")
{
document.getElementById(elementName).setAttribute("class","show");
}
else
{
document.getElementById(elementName).setAttribute("class","hide");
}
}

Related

How do you populate an option value using jQuery?

I am trying to populate a form option value if it's attribute quantity equals zero.
My goal is to add the a message to the current option value
My html is:
<select class="valid">
<option disabled="disabled" selected="selected" value="">Select Bar</option>
<option value="1" quantity="99">value 1 </option>
<option value="2" quantity="0">value 2 </option>
</select>
So far I've tried the following in jQuery but it's not working:
if($(this).attr('quantity') == '0') {
$(this).append('<span>message</span>');
}
If you don't care about preserving the original message, than you can simply say $(this).text("message"). Leave out the <span> since it cannot be rendered inside of an <option> element anyway.
if($(this).attr('quantity') == '0') {
$(this).text('message');
}
If you want to preserve the original message, you have a couple options. One would simply be to append the new message to the original, however, it may get tricky to remove it later, so I would suggest having some sort of delimiter so you can easily identify the original vs the appended message, like so:
var $option = $(this);
if($option.attr('quantity') == '0') {
$option.text($option.text().trim() + ' (message)');
}
Then, to remove the message, you can do something like this:
$option.text($option.text().slice(0, $option.text().indexOf('(')).trim());
You can populate the option with like this,
$(document).ready(function () {
$('.valid').on('change', function () {
if ($(this.options[this.selectedIndex]).attr('quantity') == 0) {
$(this.options[this.selectedIndex]).find('span').remove();
$(this.options[this.selectedIndex]).append('<span>Message</span>')
}
});
});
JSFIDDLE
I'm not entirely sure of what you're trying to achieve from your question, but you cannot add html elements to an option element. You can however change the text as follows:
$(document).on('change', '.valid', function(){
var selected = $('.valid > option:selected');
if(selected.attr('quantity') == '0'){
selected.text('something else');
}
});
if you wanted to append an error you could do so by using jQuery append() or concatenating with the original value. Alternatively if you wanted it as validation outside of the select box, you could simply assign to the value of a div by replacing the line inside of the if statement.
<select class="valid" onchange="quality(this.options[this.selectedIndex].getAttribute('quantity'));">
<option disabled="disabled" selected="selected" value="">Select Bar</option>
<option value="1" quantity="99">value 1 </option>
<option value="2" quantity="0">value 2 </option>
</select>
<span id="msg"></span>
<script type="text/javascript">
function quality(val) {
if(parseInt(val) == 0){
document.getElementById("msg").innerHTML = "Message";
}
}

Dynamic Progress Bar For Drop-Down Lists

I would like my page to display a progress bar that fills up as the user selects options on drop-down lists. So far I've been able to set variables to contain the value of the drop-down, and functions that alter the bar's value, but nothing that works together. Here's one of the drop-downs:
<select id="optionA">
<option value=" " disabled selected>Choose One...</option>
<option value="mike">Mike</option>
<option value="ryce">Andrew</option>
<option value="michael">Michael</option>
<option value="dannyl">Danny</option>
<option value="cozz">Cozz</option>
<option value="drew">Andrew</option>
<option value="pete">Pete</option>
<option value="sean">Sean</option>
<option value="dom">Dom</option>
<option value="marc">Marc</option>
<option value="lou">Lou</option>
<option value="rob">Rob</option>
</select>
For now there are two identical drop-downs, so it's id="optionA" and id="optionB". And here's the script I've tried:
var optAVal;
var optBVal;
$('#optA').on('change', function() {
var optAVal = this.value;
});
$('#optB').on('change', function() {
var optBVal = this.value;
});
if (optAVal == " " && optBVal == " ") {
$("#progressBar").attr('value','0')
;}
if (optAVal !== " " || optBVal !== " ") {
$("#progressBar").attr('value','50');
}
if (optAVal !-- " " && optBVal !== " ") {
$("#progressBar").attr('value','100');
}
You can see the idea is that if neither have selections, the bar reads 0, if one or the other are selected, it reads 50, and if both are selected it reads 100, problem is nothing's working properly. I've tried a few different combinations, including nesting the if statements in $('#optX').on('change', function() {}); and this current combination sets the progress bar to 100% on load. Appreciate the help in advance. Thanks!!!
The essential problem, in addition to small errors and typos, is that your conditionals are never called after the initial load. Thus the progress bar never gets updated.
If you use html like this:
<select id="optionA">
<option value=" " disabled selected>Choose One...</option>
<option value="mike">Mike</option>
...
</select>
<select id="optionB">
<option value=" " disabled selected>Choose One...</option>=
<option value="rob">Rob</option>
...
</select>
<progress id='progressBar' max='100' value='0'></progress>
And JQuery like this:
var doneA = false;
$('#optionA').on('change', function() {
if (!doneA) {
$("#progressBar").attr('value', $("#progressBar").prop('value')+50);
doneA = true;
}
});
var doneB = false;
$('#optionB').on('change', function() {
if (!doneB) {
$("#progressBar").prop('value', $("#progressBar").attr('value')+50);
doneB = true;
}
});
The result should be as you desire. Here's a working JSFiddle to verify: http://jsfiddle.net/wLt4z/2/
Edit 1: If you want to be more clever, you could assign each form option a shared class, like class='formOption', and craft a generic bit of JQuery to update the progress bar appropriately. For example:
$('.formOption').data("done", false);
$('.formOption').on('change', function() {
if (!$(this).data("done")) {
$("#progressBar").attr('value', $("#progressBar").prop('value')+100/$('.formOption').length);
$(this).data("done", true);
}
});
Edit 2: Updated to ensure altering a value doesn't increased the completion percentage. In both cases, this is done by means of a simple boolean flag, which in fact supersedes checking the value.

HTML onclick document.getElementById

I have a question which I am sure is simple but I have slight problem getting it to work. I have wrote a function in an external js file which has one parameter.
In my HTML I have onclick event where the arguement I want to supply is the value in a dropdown menu, hence me using document.getElementById to grab that value. But when I trigger the event it is complaining.
<select id="ddlOriginHubChinaSea" onclick="chkHub(document.getElementById('ddlOriginHubChinaSea').val())" >
<option value="Cambodia">Cambodia</option>
<option value="HK">HK</option>
<option value="Indonesia">Indonesia></option>
<option value="Shanghai">Shanghai</option>
<option value="Thailand">Thailand</option>
</select>
function chkHub(param) {
if (param != '') {
$('#txtChinaSeaAirHub').val(param);
}
else {
$('#txtChinaSeaAirHub').val('');
}
}
Try this out:
<select id="ddlOriginHubChinaSea" onchange="chkHub(this.value)" >
function chkHub(param) {
if (param.options[param.selectedIndex].value != '') {
$('#txtChinaSeaAirHub').val(param.options[param.selectedIndex].value);
}
else {
$('#txtChinaSeaAirHub').val('');
}
}
and onchange="chkHub(this)"

Disabling other dropboxes on selection of value in one

I am trying to write a function that will:
Disable the submit button when no option in a dropbox is selected (ie empty string is selected). Enable all dropboxes.
On user selection of an option in a dropbox (that is not the empty
string), disable all other drop boxes and enable the submit button.
However, as a beginner at JavaScript I have no idea how I would begin this. How would I write such code?
So my simplified HTML would be as follows :
<form id="form" name="form" method="post" action="confirmation.cshtml">
<select name="start_to_end_time" class="start_to_end_time">
<option value="1">1</option>
<option value="2">2</option>
</select>
<select name="start_to_end_time" class="start_to_end_time">
<option value="3">3</option>
<option value="4">4</option>
</select>
<button type="submit">Submit</button>
How can I write code that fulfills this function?
I think it's not a good idea to give two HTML element the same name attribute unless you use brackets [] within it. The last one may overwrite the value of the first one.
JavaScript using MooTools:
$$('.start_to_end_time').each(function(element) {
element.addEvent('click', function(ev) {
$$('.start_to_end_time').each(function(selectbox) {
if (element.getProperty('value') != '') {
$('button').setProperty('disabled', '');
$$('.start_to_end_time').each(function(b) {
if (b != element) {
b.setProperty('disabled', 'disabled');
} else {
b.setProperty('disabled', '');
}
}
} else {
$('button').setProperty('disabled', 'disabled');
$$('.start_to_end_time').each(function(b) {
b.setProperty('disabled', '');
}
}
});
});
});
I didn't test the code. You may define some methods to make it more readable.
start by loading the button as disabled:
<button id="myButton" type="submit" disabled='disabled'>Submit</button>
also, add a onchange listener to your options:
<select onchange="myJSFunction()" name="start_to_end_time" class="start_to_end_time">
<option value="3">3</option>
<option value="4">4</option>
then, write the javascript function:
function myJSFunction(){
var myButton = document.getElementById('myButton');
myButton.removeAttribute("disabled");
}
To check the selected value and disable accordingly (this must be executed in the function called by the onchange method):
var mySelect =document.getElementById('mySelect');
var mySelectedIndex = mySelect.selectedIndex;
if (mySelectedIndex==0){
mySelect.setAttribute("disabled","disabled);
}

Javascript hide and show form not working

This is a follow up question. I am trying to get a input box to be hidden when a pull-down menu has the value "tid and acc". I am at a loss why this code isn't working, any help would much appreciated! Here is a link on jfiddle: http://jsfiddle.net/Mm7c7/
<script>
$('#rule-type').change(function() {
var val = $(this).val();
if (val == 'tid and acc') {
$('#tid-acc').show();
}
else {
$('#tid-acc').hide();
}
});
</script>
<select id="rule-type">
<option value="" selected="selected">None</option>
<option value="tid">tid</option>
<option value="tid and acc">tid and acc</option>
<option value="xid">xid</option>
</select>
<input id="tid-acc">
Your script is being evaluated before your element is ready. Placing the script in a $(document).ready() or after the content it affects will solve the problem
http://jsfiddle.net/Wx8Jf/2
$(document).ready(function(){
$('#rule-type').change(function() {
var val = $(this).val();
if (val == 'tid and acc') {
$('#tid-acc').show();
}
else {
$('#tid-acc').hide();
}
});
});
Couple problems:
You'll either need to wrap the function in $(function(){}) to ensure DOM is ready, or drop it below your HTML (the former is recommended). If you don't wrap it (or drop it), then the script is executed before the elements have actually been rendered, causing $('#rule-type') to be undefined.
Your logic is incorrect (according to your explanation). Your current logic says to hide the input box when anything other than tid and acc is selected.
Working version:
<script>
$(function(){
$('#rule-type').change(function() {
var val = $(this).val();
if (val == 'tid and acc') {
$('#tid-acc').hide();
}
else {
$('#tid-acc').show();
}
});
});
</script>
<select id="rule-type">
<option value="" selected="selected">None</option>
<option value="tid">tid</option>
<option value="tid and acc">tid and acc</option>
<option value="xid">xid</option>
</select>
<input id="tid-acc" />
http://jsfiddle.net/dbrecht/QwkKf/
Take a look here for a working sample: http://jsfiddle.net/Mm7c7/1/
HTML:
<select id="rule-type">
<option value="" selected="selected">None</option>
<option value="tid">tid</option>
<option value="tid and acc">tid and acc</option>
<option value="xid">xid</option>
</select>
<input id="tid-acc">
Javascript:
$('#rule-type').change(function() {
var val = $(this).val();
if (val == 'tid and acc') {
$('#tid-acc').show();
}
else {
$('#tid-acc').hide();
}
});

Categories