Javascript and I will never be best friends.
I try to set a checkbox to checked by changing the elements from a dropdownlist.
This is the snippet
<select name="change_status_to" id="sel">
<option>....</option>
<option>....</option>
</select>
<input type="checkbox" name="do_status_change" value="on">
How could I use Javascript with the onchange-event to set the checkbox to the state checked?
You can set its .checked property:
document.getElementById("do_status_change").checked = true;
document.getElementById("do_status_change").checked = false;
However, you need to set an id; the name attribute will not suffice.
> Example <
Here is an example of why you should be friends with javascript.
JSFiddle - http://jsfiddle.net/juc7Q/1/
HTML
You're feeling toward Javascript
<select name="friends" id="friends">
<option value="love">I love JS</option>
<option value="weird">JS is weird</option>
<option value="misunderstood">Are we speaking the same language?</option>
</select>
<button id="selectWeird">Keep JS Weird</button>
<div>
<input type="checkbox" id="we_friends"> - Friends?
</div>
JavaScript
//Select this using js
var list = document.getElementById('friends');
var cb = document.getElementById('we_friends');
//Add event when change happens
list.onchange = function () {
var value = list.value;
if(value == 'love') {
alert('I knew you would come around');
cb.setAttribute('checked', '');
} else if(value == 'weird') {
alert('And I like being weird :-)!!');
cb.removeAttribute('checked');
} else {
alert('And you think I understand you?');
cb.removeAttribute('checked');
}
}
//Change to 'Weird' when I click on it
var btn = document.getElementById('selectWeird');
btn.onclick = function () {
list.options.selectedIndex = 1;
}
Related
I want the placeholder of the text input to change depending on the option selected on the select tag. Also, I wanted to change the text input to disabled on the "DOC" option.
I gathered some code examples, but none of them were showing exactly what I was looking for, so I ended up with this code below.
function changeDOC() {
var x = document.getElementById("document").value;
if (x == "doc") {
document.getElementById('docu').disabled = true;
} else if (x == "cpf") {
document.getElementsById("doc")[0].placeholder = 'CPF';
} else if (x == "cnpj") {
document.getElementsById("doc")[0].placeholder = 'CPF';
}
}
<select onchange="changeDOC" id="document">
<option value="doc" selected>DOC</option>
<option value="cpf">CPF</option>
<option value="cnpj">CNPJ</option>
</select>
<input type="text" class="form-control" id="docu" placeholder="Select a document.">
But it does nothing.
There are a few things wrong in your code, first off, there is no getElementsById() function in document, it's getElementById() since there can only ever be one element with a given ID in valid HTML (meaning you don't have to access the 0th element of the return value ([0])):
document.getElementsById("doc")[0].placeholder = 'CPF';
should be
document.getElementById("doc").placeholder = 'CPF';
Also you have to add parentheses to your markup to actually execute the function.
<select onchange="changeDOC" id="document">
Has to be
<select onchange="changeDOC()" id="document">
Also if you have DOC as selected by default, you should deactivate the element by default too, and activate it again if you choose the other options.
Here's the full code:
function changeDOC() {
var x = document.getElementById("document").value;
if (x == "doc") {
document.getElementById('docu').disabled = true;
} else if (x == "cpf") {
document.getElementById("docu").placeholder = 'CPF';
document.getElementById('docu').disabled = false;
} else if (x == "cnpj") {
document.getElementById("docu").placeholder = 'CPF';
document.getElementById('docu').disabled = false;
}
}
<select onchange="changeDOC()" id="document">
<option value="doc" selected>DOC</option>
<option value="cpf">CPF</option>
<option value="cnpj">CNPJ</option>
</select>
<input type="text" class="form-control" id="docu" placeholder="Select a document." disabled="true">
First, there is no such method as getElementsById(), it's getElementById(), which returns one element (if found). So there is no array returned from it, so passing an index isn't going to get you anything.
Next, your inline event attribute has to provide executable code that would invoke your function, but you didn't put parenthesis after the function name, so your code doesn't do this. But, you should not be using inline HTML event attributes in the first place. Instead, do all your event binding in JavaScript with the standard addEventListener() method, which actually does take a callback method reference (no parenthesis).
Now, it appears that you just want the input to have a placeholder that matches the selected item from the list, in which case, you don't need an if statement for that, just set the placeholder to the selected value directly. You only need the if to detect if the first item was selected and in that case, use the setAttribute method to set up the disabled functionality.
Also, since the select's first option is DOC and that choice should make the input disabled, you should add the disabled attribute to the input HTML statically from the start.
See the comments below for more adjustments.
// Get references to elements you'll work with just once, not upon
// each invocation of the event handler. Also, don't name or give things
// id's that are also the name of an object (ie. document)
let select = document.getElementById("list");
let input = document.getElementById("docu");
// Set up the event handler in JavaScript, not with HTML attributes like onchange
select.addEventListener("change", changeDOC);
function changeDOC() {
input.placeholder = this.value; // `this` is a reference to the select itself
if (this.value == "doc") {
input.setAttribute("disabled", "disabled");
} else {
input.removeAttribute("disabled");
}
}
<select id="list">
<option value="doc" selected>DOC</option>
<option value="cpf">CPF</option>
<option value="cnpj">CNPJ</option>
</select>
<input type="text" class="form-control" id="docu" placeholder="Select a document." disabled>
There is a lot of syntax error in your code, just figure out errors but you should also go through over it.
Number 1:
You need to call the function not just place the name.
<select onchange="changeDOC" id="document"> // Wrong
<select onchange="changeDOC()" id="document"> // Correct
Number 2:
document.getElementsById("doc") // Wrong
document.getElementById("doc") // Correct
Number 3:
In the input tag you are using id="docu" and get with ('doc')
function changeDOC() {
var x = document.getElementById("document").value;
if (x == "doc") {
document.getElementById('docu').disabled = true;
document.getElementById("docu").placeholder = 'DOC';
} else if (x === "cpf") {
document.getElementById('docu').disabled = false;
document.getElementById("docu").placeholder = 'CPF';
} else if (x === "cnpj") {
document.getElementById('docu').disabled = false;
document.getElementById("docu").placeholder = 'CNPJ';
}
}
<select onchange="changeDOC()" id="document">
<option value="doc" selected>DOC</option>
<option value="cpf">CPF</option>
<option value="cnpj">CNPJ</option>
</select>
<input type="text" class="form-control" disabled id="docu" placeholder="Select a document.">
I have removed the extra id from the select option in HTML.
In JavaScript the select variable returns the whole select node with it's children.
So I've added an event listener that on a change fires off a function with a parameter e that target's children (the one that's been selected) and add set's it's value as an attribute to the input tag.
const select = document.querySelector('select');
const input = document.querySelector('input');
select.addEventListener('change', e => {
input.setAttribute('placeholder', `Select a ${e.target.value.toUpperCase()}`);
})
<select>
<option value="doc" selected>DOC</option>
<option value="cpf">CPF</option>
<option value="cnpj">CNPJ</option>
</select>
<input type="text" class="form-control" id="docu" placeholder="Select a document." />
I want to make this textbox enabled when I choose a specific value from a select drop-down, and disabled when I select any other option.
This is my html:
<select name="status" id ="combo">
<option value="_">Please choose..</option>
<option value="Pending">Pending</option>
<option value="Process">Process</option>
<option value="Delivered" >Delivered</option>
</select>
<tr valign="baseline">
<td nowrap="nowrap" align="right" class="postage" >Postage:</td>
<input type="text" name="postage" id="textbox" >
Try this:
var select_element = document.getElementById( "combo" );
var selected = select_element.options[ select_element.selectedIndex ].value
if(selected == "Delivered"){
document.getElementById("textbox").disabled = false;
}else{
document.getElementById("textbox").disabled = true;
}
I saw the original title with jQuery but someone edited it. Anyway just incase you wondered how it's done in jQuery here it is:
$(document).ready(function () {
var $input = $('input[name=postage]');
$input.attr('disabled', 'disabled');
$('select[name=status]').on('change', function () {
$input.attr('disabled', $(this).val() != "Delivered");
});
});
demo: http://jsfiddle.net/c4rks52r/
This would be how I would do this using jQuery (demo here):
$(document).on('change', '#combo', function(){
var shouldEnable = $(this).val() !== 'Delivered';
$('#textbox').prop('disabled', shouldEnable);
});
Side note, did you ever say specifically which value being selected is the trigger for enabling? I just went with Delivered as everyone else went that route. Maybe I missed where you said that explicitly. Also, based on your description on wanting to enable it only when a specific value is selected, I assume you would want it disabled initially when the page loads. My demo has that in place.
A textarea's text will be populated with a dropdown lists selected
text.
A simple radio button list will determine which dropdown list's text should be used.
CLICK HERE FOR DEMO
The code below creates the desired effect but does not make the expected changes when an alternate radio button value is selected.
Debugging shows checked is not added to radio inputs when a new selection is made.
JQUERY
var rbl = $('#rbl input:checked').val();
$('#ddlA1,#ddlB1').change(function () {
if (rbl = 1) {
$('#txt').val($('#ddlA1 :selected').text());
} else if (rbl = 2) {
$('#txt').val($('#ddlB1 :selected').text());
}
});
HTML
<span id="rbl">
<input type="radio" id="rbl_0" name="rbl" value="1" /> 1 <br />
<input type="radio" id="rbl_1" name="rbl" value="2" /> 2 <br />
</span>
<select id="ddlA1">
<option value="1">A1 A</option>
<option value="2">A1 B</option>
<option value="3">A1 C</option>
</select>
<select id="ddlB1">
<option value="1">B1 A</option>
<option value="2">B1 B</option>
<option value="3">B1 C</option>
</select>
<textarea id="txt">LOAD TEXT</textarea>
Your code is correct but you need to modify some little things ;)
$('#ddlA1,#ddlB1').change(function () {
var rbl = $('#rbl input:checked').val();
if (rbl == 1) {
$('#txt').val($('#ddlA1 :selected').text());
} else if (rbl == 2) {
$('#txt').val($('#ddlB1 :selected').text());
}
});
Put rbl variable inside the change event
Use == instead of = on your conditionals
http://jsfiddle.net/3kXsX/5/
That's all!
Best Regards,
Something more like this
$('#rbl_0, #rbl_1, #ddlA1, #ddlB1').on('change', function() {
var dropdown = $($('#rbl_0').is(':checked') ? '#ddlA1' : '#ddlB1');
$('#txt').val(dropdown.find('option:selected').text());
});
FIDDLE
The value of rbl is set once, when that line of code runs, and not updated if the selected radio changes. Put the var rbl = ... line inside the event handler so it checks the radios when a change is made to the dropdown, ie
$('#ddlA1,#ddlB1').change(function () {
var rbl = $('#rbl input:checked').val();
if (rbl = 1) {
$('#txt').val($('#ddlA1 :selected').text());
} else if (rbl = 2) {
$('#txt').val($('#ddlB1 :selected').text());
}
});
I have a select with loads of options. (Code below shortened for sake of example).
I want it to set the value of the input textfield "hoh" to "10" when you click/select all dropdown options, except one, that should set it to 50.
I imagined something like this would work, but its not. What am I doing wrong here?
<select>
<option onselect="document.getElementById('hoh').value = '50'">Hey</option>
<option onselect="document.getElementById('hoh').value = '10'">Ho</option>
<option onselect="document.getElementById('hoh').value = '10'">Lo</option>
....
</select>
<input type="text" id="hoh" value="10">
Something like this should work:
<script>
function myFunc(val) {
if (val == '50') {
document.getElementById('hoh').value = val;
} else {
document.getElementById('hoh').value = '10';
}
}
</script>
<select onchange="myFunc(this.value)">
<option value="1">one</option>
<option value="2">two</option>
<option value="50">fifty</option>
</select>
http://jsfiddle.net/isherwood/LH57d/3
The onselect event refers to selecting (or highlighting) text. To trigger an action when a dropbox selection changes, use the onchange event trigger for the <select> element.
E.g. Since you didn't already set the value attribute of your option tags.
<select id="myselect" onchange="myFunction()">
<option value="50">Hey</option>
<option value="10">Ho</option>
<option value="10">Lo</option>
....
</select>
and somewhere inside of a <script> tag (presumably in your HTML header) you define your javascript function.
<script type="text/javascript>
function myFunction() {
var dropbox = document.getElementById('myselect');
document.getElementById('hoh').value = dropbox[dropbox.selectedIndex].value;
}
</script>
I'm not sure it's wise to repeat the same value among different options in a droplist, but you could expand on this to implement the result other ways, such as if the sole option which will have value 50 is in a certain position, you could compare the selectedIndex to that position.
you could add an onchange event trigger to the select, and use the value of an option to show in the textbox
see http://jsfiddle.net/Icepickle/5g5pg/ here
<select onchange="setValue(this, 'hoh')">
<option>-- select --</option>
<option value="10">Test</option>
<option value="50">Test 2</option>
</select>
<input type="text" id="hoh" />
with function setValue as
function setValue(source, target) {
var tg = document.getElementById(target);
if (!tg) {
alert('No target element found');
return;
}
if (source.selectedIndex <= 0) {
tg.value = '';
return;
}
var opt = source.options[source.selectedIndex];
tg.value = opt.value;
}
Try this code
var inp = document.getElementById('hoh');
sel.onchange = function(){
var v = this.value;
if( v !== '50'){
v = '10';
}
inp.value = v;
};
What I'm trying to do is this:
When a job is selected from a drop-down list, I want to populate the hourlyRate field in the totals table with an amount.
This is my dropdown list:
<fieldset>
<legend>What is your position?</legend>
<select name="job" id="job">
<option value="job0">Please select a position:</option>
<option value="job1">Server/Bartender</option>
<option value="job2">Greeter/Busser</option>
<option value="job3">Kitchen Support</option>
</select>
</fieldset>
This is my totals table:
<div id="totals">
<table width="408">
<tr>
<td width="214">Hourly Rate:</td><td width="57" id="hourlyRate"></td></tr>
</table>
</div>
This is my javascript:
var $ = function (id) {
return document.getElementById(id);
}
function rateChange () {
var rate="";
if ($('job').value == 'job0') {
rate = '0';
}
if ($('job').value == 'job1') {
rate = '12';
}
if ($('job').value == 'job2') {
rate = '10';
}
if ($('job').value == 'job3') {
rate = '11';
}
$('hourlyRate').innerHTML = "$ " + rate;
}
window.onload = function () {
$('job').onchange = rateChange();
}
So if someone selects server/bartender from the dropdown list, I want the hourlyRate field in my totals table to display $12. I cannot figure out what I am doing wrong!
It looks like you're calling your function straight away, instead of telling it to be called on the onchange event:
$('job').onchange = rateChange();
So the return value of rateChange (nothing) is assigned to the onchange event.
Try this:
$('job').onchange = rateChange;
Now the rateChange function is the function that will be run when the onchange event fires.
if you want to add an handlerfunction to your event you must not add the brackets...
you have to wirte:
$('job').onchange = rateChange;
just tried... works fine.
if you're adding the brackets the function will be called only one time in window.onload...