This is my script
<script type="text/javascript">
function showlevel1() {
var l1 = document.getElementById('default');
l1.style.display = 'block';
var l2 = document.getElementById('secondDiv');
l2.style.display = 'none';
}
function showlevel2() {
var l2 = document.getElementById('secondDiv');
l2.style.display = 'block';
var l1 = document.getElementById('default');
l1.style.display = 'none';
}
function selectHandler(select) {
if (select.value == 'count') {
showlevel2();
} else if (select.value == 'Top') {
showlevel1();
}
}
</script>
HTML:
<form>
<select id='type'>
<option value="Top">TOP</option>
<option value="count">COUNT</option>
</select>
<input type='submit' value='submit' onclick=selectHandler(this)>
</form>
<div id='default' style="display:block">
<h1>Div 1</h2>
</div>
<div id='secondDiv' style="display:none">
<h2> Div 2</h1>
</div>
When I load the page the DIV 1 does shows up, since the property is set to display:'Block' but when I perform the selection from drop down it never changes to DIV2 upon the Count selection from drop down and a submit click button?
Can anyone please help in figuring out the issue and let me know what am I doing wrong?
Thanks
Your select.value outputs submit since your this element referes to
-> <input type="submit" value="submit"/>
Why
selectHandler(this) is triggered by your submit button and not by your <select> tag, so when you perform select.value it returns submit as your text.
After seeing your question I guess you are in need of getting the select tag value.
Try this
function selectHandler(select) {
// get your drop down list element i.e select tag
var selected = document.getElementById('type');
if (selected.value === 'Count') {
showlevel2();
}
else if (selected.value === 'Top') {
showlevel1();
}
}
After seeing your comments
The problem is your using type="submit"
which posts to the same page when your click on it. Change it to type="button"
<input type='button' value='submit' onclick="selectHandler()">
function selectHandler() {
// get your drop down list element i.e select tag
var select = document.getElementById('type');
if (select.value === 'Count') {
showlevel2();
}
else if (select.value === 'Top') {
showlevel1();
}
}
Or
<input type='submit' value='submit' onclick="return selectHandler()">
function selectHandler() {
var select = document.getElementById('type');
if (select.value === 'Count')
showlevel2();
else if (select.value === 'Top')
showlevel1();
return false;
}
js fiddle here http://jsfiddle.net/QGsza/68/
Just taking a quick look, it seems that you have checked for a lowercase value 'count' instead of 'Count'.
i.e. replace
select.value == 'count'
with
select.value == 'Count'
in your onclick on the button, you're passing "this" which would be a pointer to the button itself.
change it to document.getElementById('type') because it looks like your selectHandler is expecting the select element
also, change the button from "submit" to "button" as submit will tell the browser to make a request.
the first DIV:
<div style="display:block;" id="first">
the second DIV:
<div style="display:none;" id="second">
and on the function add:
document.getElementById('first').style.display = 'none';
document.getElementById('second').style.display = 'block';
Related
I am having an issue; where when I click a button that takes the value from a drop-down list, it is supposed to show the div assigned to his matching value.
So far, my code do as intended, it shows the corresponding div, but then it reverts and hides it back 3 seconds after. It could be a simple mistake, your help is appreciated.
At the head:
var e = document.getElementById("graph_req_ID");
var indexValue = e.options[e.selectedIndex].value;
var strValue = e.options[e.selectedIndex].text;
function getGraphReq(){
if (strValue == "Default") {
graph3.style.display = "block";
} else {
graph3.style.display = "none";
}
}
My button:
<button onclick="getGraphReq()"></button>
The hidden div:
<div id="graph3">
<h4>this content should show after clicking the button</h4>
</div>
function getGraphReq(){
var e = document.getElementById("graph_req_ID");
var indexValue = e.options[e.selectedIndex].value;
var strValue = e.options[e.selectedIndex].text;
if (strValue == "Default") {
graph3.style.display = "block";
} else {
graph3.style.display = "none";
}
}
<select id="graph_req_ID">
<option value="Default">Default</option>
<option value="Default">foo</option>
</select>
<button onclick="getGraphReq()">Click me</button>
<div id="graph3">
<h4>this content should show after clicking the button</h4>
</div>
I moved those variables into the function. Then when you execute the function it will assign correct values to the variables. Is this the expected output you need.
Not sure what the issue with your code, but is that the intended behaviour?
var e = document.getElementById("graph_req_ID");
var indexValue = e.options[e.selectedIndex].value;
function getGraphReq() {
var strValue = e.options[e.selectedIndex].text;
if (strValue == "Default") {
graph3.style.display = "block";
} else {
graph3.style.display = "none";
}
}
getGraphReq();
<select id='graph_req_ID'>
<option value='Default'>Default</option>
<option value='Other' selected>Other</option>
</select>
<button onclick="getGraphReq()">getGraphReq</button>
<div id="graph3">
<h4>this content should show after clicking the button</h4>
</div>
If the element should not be visible onload and only by the click event then:
<div id="graph3" style="display:none">
Your code worked for me. Possibly something else in the file causing your issue. Hard to tell with what you posted.
I'm trying to set the value of a checkbox, if checked the value is active, but if unchecked the value is disabled.
The next code works for text, the text changes when the checkbox is checked or unchecked, but the value that is posted to the database is null when the checkbox is unchecked.
HTML
<input type="checkbox" name="cat_status" class="inline checkbox" id="checkbox" checked value="active" onclick="cat_check()">
<label id="text" style="display:Active">Active</label>
JS
function cat_check() {
var checkBox = document.getElementById('checkbox');
var text = document.getElementById('text');
if (checkBox.checked == false) {
text.style.display = "inline";
document.getElementById('checkbox').value = "active";
} else {
text.style.display = "none";
document.getElementById('checkbox').value = "disable";
}
}
I expect the value posted to database to be disabled when the checkbox is unchecked, but currently getting a null.
Update:
Added a fixed version including the AJAX call based on the provided feedback of the answers. This is just in case someone fall into the same issue.
If you play with the example on the bottom of serialize() documentation you will see that value is not appended for checkboxs that are uncheked. You will have to do it manually. Maybe this can help you: how can I override jquery's .serialize to include unchecked checkboxes
HTML
<form method="post" class="add_sub_categories">
<input type="checkbox" name="cat_status" class="inline checkbox" id="checkbox" checked value="active" onclick="cat_check()">
<label id="text" style="display:Active">Active</label>
<a class="btn btn-xs btn-info save_main_cat">GO!</a>
</form>
JS
function cat_check() {
var checkBox = document.getElementById('checkbox');
var text = document.getElementById('text');
if (checkBox.checked == true) {
text.style.display = "inline";
} else {
text.style.display = "none";
}
}
AJAX
$(document).ready(function() {
$(".save_main_cat").click(function() {
var data = $('.add_main_categories').serialize();
/* This code will include the value for the checkbox when unchecked */
$(".add_main_categories input:checkbox:not(:checked)").each(function(e) {
data += "&"+this.name+'=disable';
});
$.ajax({
type: 'POST',
url: "<?= base_url() ?>admin_ajx/categories_ajx/update_main_categories",
data: data,
success: function() {
$('#addCat').modal('hide');
$(".add_main_categories")[0].reset();
dttable.destroy();
$(document).ready(function() {
main_cat(), main_cat_option(), dt_tables();
});
}
});
});
});
If I understood correctly, the problem is on your click handler. When you unchek the checkbox by clicking on it, the checked property will be false when you observe it inside the click handler. And you are doing this:
if (checkBox.checked == false)
{
text.style.display = "inline";
document.getElementById('checkbox').value = "active";
}
So, in other words, you are setting the value to active when the checkbox is unchecked, but instead, that setting should be associated to checked state equal to true. I believe you are looking for something like this:
function cat_check()
{
var checkBox = document.getElementById('checkbox');
var text = document.getElementById('text');
if (checkBox.checked === true)
{
text.style.display = "inline";
checkBox.value = "active";
}
else
{
text.style.display = "none";
checkBox.value = "disable";
}
console.log(checkBox.value);
}
.as-console {background-color:black !important; color:lime;}
<input type="checkbox" name="cat_status" class="inline checkbox" id="checkbox" checked value="active" onclick="cat_check()">
<label id="text" style="display:inline">Active</label>
There are other fixs on the code also:
A) The initial display:Active is not a valid CSS configuration in reference to <label id="text" style="display:Active">Active</label>. So I changed it to display:inline.
B) Use the already defined variable checkBox inside the click handler instead of doing multiple calls to document.getElementById('checkbox').
You can set value 1 , as if it is checked then value posts 1 otherwise can checked null or not;
// In view
//On post time you can check if value is 1 then cheked otherwise null
I am adding multiple controls on an .aspx page from the .vb page based on certain conditions.
My code looks like following:
Dim sb As New StringBuilder
sb.Append("<table border='0'cellpadding='0' cellspacing='0' width='50%' class ='tabledata' id='tblContent'>")
For Each item As myObject In myLst
sb.Append("<tr><td style='width:50%;' valign='top'>")
sb.Append("<textarea id=txt_comments" & i & " name='txt_comments' rows='5' cols='60'></textarea></td>")
sb.Append("<td style='width:15%' valign='top' align='center'><select ID = validate" & i & " name=ValidateValues style ='border:1;width:150px'><option value = ''>Select</option><option value = 'Yes'>Yes</option><option value = 'No'>No</option><br /><br /></td>")
sb.Append("</tr><tr>")
Next
sb.Append("</table>")
myContent.InnerHtml = sb.ToString
So here I am creating <textarea> and <select> dynamically and adding them to my div(myContent)
<div id="structuredContent" runat="server">
</div>
I have a button next where I need to validate for few conditions.
My validation rule is:
User has to select either yes or no from the dropdown(<select>)
If user select 'yes', they have to enter text in
<textarea>(minimum1 character, maximum 1000 characters)
If user select 'No', <textarea> should be disabled.
I am trying to validate like following:
function validateComments() {
var errorcheck = 0;
$("[id^=txt_comments]").each(function () {
var comment = $.trim($(this).val());
$("[id^=validate]").each(function () {
debugger;
var value = $(this).val();
if (comment == 0 && value == "Yes") {
debugger;
errorcheck = 1;
}
});
}); if (errorcheck == 1) {
//show error message
}
else {
ErrorHide();
return true;
}
}
I am able to validate only for one control(which is textarea) from the above code.
The textbox and respective dropdown should be validated along.
How do I add validation for dropdown and can I combine with in the same function.
Any help?
Thanks in advance.
I don't know how do you expect this like if (comment == 0) { to work.
You'll always get a string as a value and checking it with 0 would always return false. Rather you need to check it with "".
And to enable/disable textarea you'll have to attach an event to select tag and do whatever you want to do.
here is an example
$("#d").change(function(){
if($(this).val() === 'n'){
$("#t").prop('disabled', 'disabled')
}else{
$("#t").prop('disabled', false)
}
});
$('body').on('click', '#b', function() {
var text = $.trim($("#t").val());
if(text === "" && !$("#t").prop('disabled')){
alert("yo! not valid")
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<select id="d">
<option value="0">Select</option>
<option value="y">Yes</option>
<option value="n">No</option>
</select>
<textarea maxlength="50" id="t"></textarea>\
<button id="b">Validate</button>
In a js code, i created 3 buttons --- button 1...button 2...button 3
and 3 input fields --- input field 1...input field 2...input field 3
From the beginning of the script all buttons are disabled
button 1 will only be activated (you can click on it) when input field 1 and 2 have numerated values
button 2 will only be activated when input field 1 and 3 have numerated values
button 3 will only be activated when input field 2 and 3 have numerated values.
My problem is when i entered a numerated value for input field 1 and 2, button 1 will not activate (in-clickable) even though it was suppose to
And lets say i redid my code and got my whole code backwards so, at the beginning of my script all the buttons were not disabled (you could click on them). Then i made a simple conditional statement like so
input field 1 = if1
input field 2 - if2
if (if1.length = 0 || isNaN(if1) && if2.length = 0 || isNaN(if2) ) {
document.getElementById("button 1").disable = true;
}
Button 1 will not immediately disable until the user clicks on the button. And if the user were to re-enter the appropriate value type in input field 1, button 1 will not activate (be-clickable) because apparently its permanently disabled.
So down to summary, I'm asking if there is a way to make JavaScript be instantly interactive. Such as a web browser search bar. The moment you type something, you immediately get a list of possible questions and when you don't type anything in them the list disappears and the browser regains its original state.
Any Advice/help shall be greatly appreciated
Due to Life and its problems my code some how got deleted. Thus the lack of code and bunch of words. Sorry.
Generic solution (using attributes)
You can check the answer below which is using oninput event and the attributes to handle your situation effectively.
I have added a data-target attribute to link the elements together to fit with your requirement.
For an instance, to match the rule button 1 will only be activated (you can click on it) when input field 1 and 2 have numerated values, data-target of button1 is id of textbox 1 & 2.
Working snippet:
function checkInput() {
var dataTarget = 'data-target';
var elm = event.target;
var targetAttrs = getAttr(elm, dataTarget);
if(targetAttrs) {
var targetButtons = targetAttrs.split(',');
for(var i = 0; i < targetButtons.length; i++) {
var button = document.getElementById(targetButtons[i]);
targetAttrs = getAttr(button, dataTarget);
if(targetAttrs) {
var targetTextBoxes = targetAttrs.split(',');
var valid = true;
for(var j = 0; j < targetTextBoxes.length; j++) {
var textBox = document.getElementById(targetTextBoxes[j]);
if(textBox) {
valid = isValidNumber(textBox.value);
}
if(!valid) {
break;
}
}
button.disabled = !valid;
}
}
}
}
function isValidNumber(val) {
return (val && val.length > 0 && !isNaN(val));
}
function getAttr(elm, name){
var val;
if(elm) {
var attrs = elm.attributes;
for(var i = 0; i < attrs.length; i++) {
if(attrs[i].name === name) {
val = attrs[i].value;
break;
}
}
}
return val;
}
<div>
<input type="text" id="textBox1" oninput="checkInput()" data-target="button1,button2" />
</div>
<br/>
<div>
<input type="text" id="textBox2" oninput="checkInput()" data-target="button1,button3" />
</div>
<br/>
<div>
<input type="text" id="textBox3" oninput="checkInput()" data-target="button2,button3" />
</div>
<br/>
<input type="button" id="button1" value="Submit" data-target="textBox1,textBox2" disabled />
<input type="button" id="button2" value="Submit" data-target="textBox1,textBox3" disabled />
<input type="button" id="button3" value="Submit" data-target="textBox2,textBox3" disabled />
Note: With this code, when you add more elements, you don't need to change/add any Javascript code. Just add the elements and attributes
var field1 = document.getElementById('if1');
var field2 = document.getElementById('if2');
var field3 = document.getElementById('if3');
var button1 = document.getElementById('button1');
var button2 = document.getElementById('button2');
var button3 = document.getElementById('button3');
field1.addEventListener('input', function(){
if(this.value!= '' && field2.value!='')
button1.disabled = false;
else
button1.disabled = true;
if(this.value!= '' && field3.value!='')
button2.disabled = false;
else
button2.disabled = true;
});
field2.addEventListener('input', function(){
if(this.value!= '' && field1.value!='')
button1.disabled = false;
else
button1.disabled = true;
if(this.value!= '' && field3.value!='')
button3.disabled = false;
else
button3.disabled = true;
});
field3.addEventListener('input', function(){
if(this.value!= '' && field1.value!='')
button2.disabled = false;
else
button2.disabled = true;
if(this.value!= '' && field2.value!='')
button3.disabled = false;
else
button3.disabled = true;
});
<input type="text" id="if1">
<input type="text" id="if2">
<input type="text" id="if3">
<br>
<button type="button" id="button1" disabled="true">Button1</button>
<button type="button" id="button2" disabled="true">Button2</button>
<button type="button" id="button3" disabled="true">Button3</button>
Here is how you do it
Disabling a html button
document.getElementById("Button").disabled = true;
Enabling a html button
document.getElementById("Button").disabled = false;
Demo Here
Edited
Try this...
You apply addEventListener to that DOM object:
document.getElementById("IDTeam").addEventListener("change", function() {//call function here});
For IE
document.getElementById("IDTeam").attachEvent("onchange", function() {//call function here} );
Hello I have a site with several Questions and i want an survey to click throw a few "divs" and with a check box if they want to give no answer:
!!! Every thing works but if i type in 0 in the input field the alert comes but then i Can't get further ? WHY !!!
My code for the Checkbox:
<input type="checkbox" id="CheckBoxFeld" name="CheckBox2" >
My Code For the Next Button:
<input type="button" value="Next">
My Code for the TEST:
function check2(){
var field = document.Survey.Answer2.value;
var checkbox2 = document.Survey.CheckBox2.checked;
if (field == 0 && checkbox2 == false){
alert("Please answer question 2");
}
else{
showHideDiv('Question2', 'Question3');
}
}
And my Code for the ShowHide Function:
// Show and Hide Div
function showHideDiv(idHide, idShow){
//document.getElementById(idShow).style.display = "block";
//document.getElementById(idHide).style.display = "none";
document.getElementById(idHide).style.visibility = "hidden";
document.getElementById(idShow).style.visibility = "visible";
}
Try checking the length of the value:
function check2(){
var field = document.Survey.Answer2.value;
var checkbox2 = document.Survey.CheckBox2.checked;
if (field.length == 0 && checkbox2 == false){
alert("Please answer question 2");
}
else{
showHideDiv('Question2', 'Question3');
}
}
Try using, onclick="check2();" instead of onclick="onclick=check2();"
<input type="button" class="Button" value="Next" onclick="check2();">
Javascript:
function check2(){
var field = document.Survey.Answer2.value;
var checkbox2 = document.Survey.CheckBox2.checked;
if (field == 0 && checkbox2 == false){
alert("Please answer question 2");
}
else{
showHideDiv('Question2', 'Question3');
}
return false;
}
A few issues
poor practice and illegal html to wrap a button in a link
if you use a link, return false to avoid the HREF to be followed. In this case the browser would likely go to top and some browsers would partially unload the page, making for example animations stop
Like this
Next
OR
<input type="button" onclick="check2()" value="Next">
using
function check2(){
var field = document.Survey.Answer2.value;
var checkbox2 = document.Survey.CheckBox2.checked;
if (field == 0 && !checkbox2){
alert("Please answer question 2");
}
else{
showHideDiv('Question2', 'Question3');
}
return false;
}
But only if your field contains 0.
If you want to test if it is empty, you need field.length==0 instead