I need to apply/remove to an input field according to a user's selection in a separate drop down form - but I can't figure out how to target the input's class.
I need to add/remove the 'pageRequired' class from this input:
<input type="text" title="Company Required" name="customfields-tf-2-tf" class="inputclass pageRequired textInput" id="customfields-tf-2-tf" />
When the user selects one of two options from a drop down field. For example:
<select class="dropdown" name="customfields-s-1-s" id="customfields-s-1-s" >
<option value="Owner"<?php if(in_array("Owner",$temp_values)) { ?> selected='selected'<?php } ?>> Owner</option>
<option value="Broker"<?php if(in_array("Broker",$temp_values)) { ?> selected='selected'<?php } ?>> Broker</option>
</select>
If the user selects broker than I want to add the pageRequired class to the first input field and remove it if the user selects Owner.
EDIT- Ok, so here is the code I am working with:
<script type="text/javascript">
function changeClass(myDropdown) {
if (#customfields-s-1-s.selectedIndex == 1 ) {
$('#customfields-tf-2-tf').addClass('pageRequired');
}
else {
$('#customfields-tf-2-tf').removeClass('pageRequired');
}
}
</script>
If you don't want to use JQuery you can also do this with just plain JavaScript:
<script>
function changeClass(obj) {
var input = document.getElementById("customfields-tf-2-tf");
if(obj.value == 'Broker') {
input.className = input.className.replace('pageRequired','');
}
else if(obj.value == 'Owner') {
input.className = input.className + ' pageRequired';
}
}
</script>
<input title="Company Required" id="customfields-tf-2-tf" class="inputclass pageRequired textInput" type="text">
<br>
<select name="matt" onchange="changeClass(this)">
<option value="Owner">Owner</option>
<option value="Broker">Broker</option>
</select>
This can be done very simply using jquery:
Just add the onchange event to your dropdown and then call a function that either removes the class or adds it depending on the dropdown selection
<select class="dropdown" name="customfields-s-1-s" id="customfields-s-1-s" onchange="javascript:changeClass(this);" >
function changeClass(myDropdown) {
if (myDropdown.selectedIndex == 1 ) {
$('#customfields-tf-2-tf').addClass('pageRequired');
}
else {
$('#customfields-tf-2-tf').removeClass('pageRequired');
}
}
Here are the links on use:
http://api.jquery.com/addClass/
http://api.jquery.com/removeClass/
Related
I want to check whether any field is changed or not excluding few field on form.For this I tried following one.
$('#FormId').not('#elementId').data("changed")
But it is not excluding the element with id 'elementId'.
You can do something like the following:
// this binds the following function on any inputs type=text under #FormId
$('#FormId input[type=text]')bind("change", function(){
// do something
});
// You can add more elements, or classes by adding commas to the selector
$('#FormId input[type=text], .anotherclass, .onemoreclass')bind("change", function(){
.
.
.
.
I think you want to check whether form data change it or not
here is one approach i have use.
Create one Variable like: oldForm save in ready with old value
Create on change event for all input any change it will trigger
below is code suggestion for same
var oldFormData = '';
$(function () {
oldFormData == $('#FormId').serialize();
$('form :input').on('change input', function () {
var isChange = $('#FormId').serialize() !== origForm
});
})
Here's a quick and dirty example.
Let's say you want to mark the inputs that you want to track with a data attribute (data-change-tracking in this example).
HTML
<form action="/echo/html/" method="post">
<p>
<label>A text input</label>
<input data-change-tracking="true" value="abc"/>
</p>
<p>
<label>A select</label>
<select data-change-tracking="true">
<option value="1">option 1</option>
<option value="2">option 2</option>
</select>
</p>
<p>
<label>A textarea</label>
<textarea data-change-tracking="true">old</textarea>
</p>
<p>
<label>Not tracked</label>
<input value="123" />
</p>
</form>
Then, let's just add a dirty class when the input has changed from the previous value:
Javascript
$(function() {
$('[data-change-tracking]').each(function(){
$(this).data('previousValue', this.value);
});
$('form').on('change', '[data-change-tracking]', function(ev) {
if (ev.target.value !== $(ev.target).data('previousValue')) {
$(ev.target).addClass('dirty');
} else {
$(ev.target).removeClass('dirty');
}
});
});
The code I am currently trying to work out is I have one drop down box that is a required drop-down. If "Complete" is selected from that drop down box a text box appears. If "Abandon" is selected from that drop down box a second drop down box appears with other options.
I am trying to add validation onto those 2nd options after the first drop down is selected. In my code I have the first drop down box "ActionDD" marked as a required field. But I can not do that with the textbox "REMtextBox" or the "ReasonDD" drop down box since they will never appear at the same time.
Here is the code for my form
<form name=StudentForm action="javascript:window.close();">
<div class="DDbox">
<select name="Action" id="ActionDD" required onchange="showHide()">
<option value="">Action:</option>
<option value="complete">Complete</option>
<option value="abandon">Abandon</option>
<option value="transfer">Transfer</option>
</select>
</div>
<br>
<div class="COMPLETEbox" id="COMPLETEbox" >
<input class="hidden-items" type="text" name="RemNUM" id="REMtextBox" placeholder="Remedy Number" min="1" maxlength="10" style="display:none;"/><br>
<select class="hidden-items" name="Reason" id="ReasonDD" style="display:none;">
<option value="">Reason:</option>
<option value="NoShow">No Show</option>
<option value="Unfixable">Unfixable</option>
<option value="other">Other</option>
</select><br><br>
<br>
<input type="submit" value="submit" onclick="checkform();">
</div>
</form>
Then here is the code I have been working on for my JavaScript to check conditions when the Submit button is pressed.
function checkform() {
if (document.getElementById('ActionDD').value ="abandon" && (document.getElementById('ReasonDD').value =""))
{
validationMessage = validationMessage + 'Enter Reason';
valid = false;
}
else valid = true;
}
</script>
I am looking for a solution for how to check if the first drop down has a value selected, then whatever corresponding textbox or drop down appears from the choice that was made in the first drop down has a value selected.
Thanks in advance for any help.
Try the below code.
Idea is to set/remove the 'required' attribute during onchange of the ActionDD drop-down. Hope it helps.
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title>HTML code with text-boxes and drop-downs</title>
<script type="text/javascript">
var actionBox,
reasonBox,
completeBox,
remTextBox,
selectedAction,
isFormValid,
validationMessage = "Not all required fields are filled in; ";
function init() {
actionBox = document.getElementById('ActionDD');
reasonBox = document.getElementById('ReasonDD');
completeBox = document.getElementById('COMPLETEbox');
remTextBox = document.getElementById('REMtextBox');
selectedAction = actionBox.value;
remTextBox.style.display = 'none';
remTextBox.removeAttribute("required");
reasonBox.style.display = 'none';
reasonBox.removeAttribute("required");
isFormValid = false;
}
function checkform() {
// Include other logic if needed here...
}
function showHide() {
init();
if (selectedAction == 'complete') {
remTextBox.style.display = 'block';
remTextBox.setAttribute("required", "required");
}
else if (selectedAction == 'abandon') {
reasonBox.style.display = 'block';
reasonBox.setAttribute("required", "required");
}
}
</script>
<style>
</style>
</head>
<body>
<form name="StudentForm">
<div class="DDbox">
<select name="Action" id="ActionDD" required onchange="showHide()">
<option value="">Action:</option>
<option value="complete">Complete</option>
<option value="abandon">Abandon</option>
<option value="transfer">Transfer</option>
</select>
</div>
<br>
<div class="COMPLETEbox" id="COMPLETEbox">
<input class="hidden-items" type="text" name="RemNUM" id="REMtextBox" placeholder="Remedy Number" min="1" maxlength="10" style="display:none;" /><br>
<select class="hidden-items" name="Reason" id="ReasonDD" style="display:none;">
<option value="">Reason:</option>
<option value="NoShow">No Show</option>
<option value="Unfixable">Unfixable</option>
<option value="other">Other</option>
</select>
<br>
<br>
<br>
<input type="submit" value="submit" onclick="checkform();">
</div>
</form>
</body>
</html>
You have a little mistake in your JavaScript validation function,
instead of a comparison (x==y) you did an assignment (x=y).
In addition to that, there is a slightly different technique for getting aselectbox selected value.
This is your code with a little change:
function checkform() {
var action = document.getElementById('ActionDD'),
reason = document.getElementById('ReasonDD');
if (action.options[action.selectedIndex].value =="abandon" && reason.options[reason.selectedIndex].value =="")
{
validationMessage = validationMessage + 'Enter Reason';
valid = false;
}
else valid = true;
}
Hope it helps a bit.
Try this.
function checkform() {
if (document.getElementById('ActionDD').value =="abandon" && (document.getElementById('ReasonDD').value ==""))
{
//Your validation message
return false;
}
else return true;
}
</script>
onchange()
function showHide() {
if(document.getElementById('ActionDD').value =="abandon")
{
document.getElementById("ReasonDD").style.display= 'block';
document.getElementById("ReasonDD").required = true;
}
else
document.getElementById("ReasonDD").style.display= 'none';
}
Change your html little bit.Remove checkform() from button and add to form as shown below.
<form name=StudentForm onsubmit="return checkform()" action="javascript:window.close();">
Im having trouble having code onchange inside onchange event.
some works and some dont work due to that.
<script>
$(document).on('change', '.sellkop', function() { // this is radio button
if ($("#rs").is(':checked')) {
$("#text_container").after(price_option());
};
if ($("#rk").is(':checked')) {
$("#price_container").remove();
$("#licensenumber_c").css({"display": 'none'
});
};
});
$('#category_group').on('change', function() { // this is select options
if ($(this).val() == 101) {
$("#underKategory").css({"display": 'none'});
$("#modelcontainer").remove();
$(".toolimage").css({ "display": 'block'});
$('.sellkop').on('change', function() { // this is radio button
if ($("#rs").is(':checked')) {
$("#licensenumber_c").css({"display": 'block'});
$(".toolimage").css({"display": 'block' });
} else {
$(".toolimage").css({"display": 'none'});
}
});
} else {
$(".bilar").remove();
$(".toolimage").css({ "display": 'none'});
}
if ($(this).val() == 102) {
$(".houses_container").remove();
$(".toolimage").css({"display": 'none'});
$("#underKategory").css({"display": 'inline-block'});
$("#modelcontainer").remove();
}
///............many other values continue
});
</script>
i know there is better way to manage this code and simplify it , how can i do it ?
EDIT:
what i want is : if i select an option , then get values to that option, then under this category option there is radio buttons , then every check button i need to get some data displayed or removed
here is a fiddle there looks my problem by jumping from categories when i select buy or sell , so
if i select category-->check buy -->then select others . i dont get same result as if i select directly cars ---> buy
I have never resorted to even two answers before (let alone three), but based on all the comments, and in a desire to keep things simple another solution is to data-drive the visibility of other items based on selections, using data- attributes to store the selectors on the options and radio buttons.
JSFiddle: http://jsfiddle.net/TrueBlueAussie/4s5rwce2/28/
e.g the HTML for the select becomes
<select name="category_group" id="category_group">
<option value="0">choose category</option>
<option value='101' id='cat101' data-show="#sellbuy,.cars,.toolimage,#licenscontainer">cars</option>
<option value='102' id='cat102' data-show="#sellbuy,#underKategory">others</option>
</select>
and the radio buttons like this:
<input id='rs' type='radio' class='radio sellkop' value='s' name='type' checked='checked' data-show="#price_container,.cars,.toolimage"/>
The code becomes very simple then, simply applying the filters specified in the selected items.
$(document).on('change', '.sellkop', function () { // this is radio button
// Hide defaults
$("#price_container,.cars,.toolimage").hide();
// Show the items desired by the selected radio button
$($(this).data("show")).show();
});
$('#category_group').on('change', function () { // this is select options
// Get the various possible data options and decide what to show/hide based on those
var $this = $(this);
var value = $this.val();
// Get the selected option
var $li = $('option[value='+ value+']', $this);
// Hide all the defaults first
$('#licenscontainer,.cars,.toolimage,.sell,#underKategory').hide();
// Now show any desired elements
$($li.data('show')).show();
// Fire change event on the radio buttons to ensure they change
$('.sellkop:checked').trigger('change');
});
This is a very generic solution that will allow very complex forms to turn on/off other elements as required. You can add data-hide attributes and do something similar for those too if required.
Note: This was an attempt to fix the existing style of coding. I have posted an alternate answer showing a far simpler method using hide/show only.
A few problems.
If you must nest handlers, simply turn them off before you turn them on. Otherwise you are adding them more than once and all the previously recorded ones will fire as well.
Your HTML strings are invalid (missing closing </div>)
You can simply use hide() and show() instead of all the css settings. You should use css styling for any specific element styling requirements (e.g. based on classes).
You need to replace specific divs, rather than keep using after, or you progressively add more html. For now I have use html to replace the content of the #text_container div.
HTML in strings is a maintenance nightmare (as your example with missing </div> shows). Instead use templates to avoid the editing problems. I use dummy script blocks with type="text/template" to avoid the sort of problems you have found. That type means the browser simply ignores the templates.
JSFiddle: http://jsfiddle.net/TrueBlueAussie/4s5rwce2/17/
HTML (with templates)
<script id="saljkop">
<div class='sex sell' id='sellbuy' >
<label ><input id='rs' type='radio' class='radio sellkop' value='s' name='type' checked='checked'/> Sell </label>
<label ><input id='rk' type='radio' class='radio sellkop' value='k' name='type'/>buy</label>
</div>
</script>
<script id="price_option">
<div class="container" id = "price_container">
<div>
<label><input class="price_option" name="price_opt" value="1" type="radio"/> Fix </label>
<label class="css-label"><input class="price_option" name="price_opt" value="2" type="radio"/> offer </label>
</div>
</div>
</script>
<script id="cars">
<div class="cars" >
<div id="licenscontainer" ><div id="licensenumber_c">
<input id="licensenumber" placeholder="Registrer number" type="text" value="" />
</div>
</div>
</div>
</script>
<div id="categories">
<select name="category_group" id="category_group">
<option value="0">choose category</option>
<option value='101' id='cat101'>cars</option>
<option value='102' id='cat102'>others</option>
</select>
</div>
<div id="underKategory">sthis is subcategory</div>
<div id="toolimage1" class="toolimage">dddddd</div>
<div id="text_container" class="text_container">textttttt</div>
New jQuery code:
$(document).on('change', '.sellkop', function () { // this is radio button
console.log('.sellkop change');
if ($("#rs").is(':checked')) {
$("#text_container").html($('#price_option').html());
};
if ($("#rk").is(':checked')) {
$("#price_container").remove();
$("#licensenumber_c").hide();
};
});
$('#category_group').on('change', function () { // this is select options
if ($(this).val() == 101) {
$(".sell").remove();
$("#categories").after($('#saljkop').html());
$("#sellbuy").after($('#cars').html());
$("#text_container").html($('#price_option').html());
$("#underKategory").hide();
$(".toolimage").show();
$('.sellkop').off('change').on('change', function () { // this is radio button
if ($("#rs").is(':checked')) {
$("#licensenumber_c").show();
$(".toolimage").show();
} else {
$(".toolimage").hide();
}
});
} else {
$(".cars").remove();
$(".toolimage").hide();
}
if ($(this).val() == 102) {
$(".sell").remove();
$("#categories").after($('#saljkop').html());
$("#text_container").html($('#price_option').html());
$(".toolimage").hide();
$("#underKategory").show();
}
///............many other values continue
});
Now if you prefer to not nest handlers (recommended), just add to your existing delegated event handler for the radio buttons:
$(document).on('change', '.sellkop', function () { // this is radio button
console.log('.sellkop change');
if ($("#rs").is(':checked')) {
$("#text_container").html($('#price_option').html());
$("#licensenumber_c").show();
$(".toolimage").show();
};
if ($("#rk").is(':checked')) {
$("#price_container").remove();
$("#licensenumber_c").hide();
$(".toolimage").hide();
};
});
JSFiddle: http://jsfiddle.net/TrueBlueAussie/4s5rwce2/20/
Note: This was a second answer, hoping to simplify the overall problem to one of hiding/showing existing elements. I have posted a third(!) answer that takes it to an even simpler scenario using data- attributes to provide the filter selections.
I am adding a second answer as this is a complete re-write. The other answer tried to fix the existing way of adding elements dynamically. I now think that was simply a bad approach.
The basic principal with this one is to have very simple HTML with the required elements all present and simply hide/show the ones you need/ Then the selected values are retained:
This uses the multi-structure to effectively hide.show the licence field based on two separate conditions.
JSFiddle: http://jsfiddle.net/TrueBlueAussie/4s5rwce2/23/
Html (all element s present, just the ones you do not need hidden):
<div id="categories">
<select name="category_group" id="category_group">
<option value="0">choose category</option>
<option value='101' id='cat101'>cars</option>
<option value='102' id='cat102'>others</option>
</select>
<div class='sex sell' id='sellbuy' style="display: none">
<label>
<input id='rs' type='radio' class='radio sellkop' value='s' name='type' checked='checked' />Sell</label>
<label>
<input id='rk' type='radio' class='radio sellkop' value='k' name='type' />buy</label>
</div>
<div class="cars" style="display: none">
<div id="licenscontainer">
<div id="licensenumber_c">
<input id="licensenumber" placeholder="Registrer number" type="text" value="" />
</div>
</div>
</div>
</div>
<div id="underKategory">sthis is subcategory</div>
<div id="toolimage1" class="toolimage">dddddd</div>
<div id="text_container" class="text_container">
<div class="container" id="price_container" style="display: none">
<div>
<label>
<input class="price_option" name="price_opt" value="1" type="radio" />Fix</label>
<label class="css-label">
<input class="price_option" name="price_opt" value="2" type="radio" />offer</label>
</div>
</div>
</div>
jQuery:
$(document).on('change', '.sellkop', function () { // this is radio button
if ($("#rs").is(':checked')) {
$("#price_container").show();
$(".cars").show();
$(".toolimage").show();
};
if ($("#rk").is(':checked')) {
$("#price_container").hide();
$(".cars").hide();
$(".toolimage").hide();
};
});
$('#category_group').on('change', function () { // this is select options
if ($(this).val() == 101) {
$(".sell").hide();
$("#sellbuy").show();
$(".cars").show();
$("#underKategory").hide();
$(".toolimage").show();
$('#licenscontainer').show();
} else {
$('#licenscontainer').hide();
$(".cars").hide();
$(".toolimage").hide();
}
if ($(this).val() == 102) {
$(".sell").hide();
$("#sellbuy").show();
$(".toolimage").hide();
$("#underKategory").show();
$(".cars").hide();
}
$("#price_container").toggle($("#rs").is(':checked'));
///............many other values continue
});
I have written this code for fetching data on submission of drop down menu, it is working on submit button click, but now I want this to work only on change of value in drop down menu, here is my working code.
<script language="javascript">
function validFormDataCity() {
if (document.getElementById("jobsbycitymenu").value == "Not Selected") {
alert("Please select a City.");
document.citysearch.jobsbycitymenu.focus();
return false;
}
}
</script>
<div id='jobsbycity'>
<form id="citysearch" name="citysearch" method="POST" action="jobs-by-city-results">
<p id='jobsbycitytitle'>Jobs by City</p>
<select name="city" id='jobsbycitymenu'>
<option value="Not Selected">---Select City---</option>
<option value='Abbottabad'>Abbottabad</option>
<option value='Arifwala'>Arifwala</option>
<option value='Attock'>Attock</option>
<option value='Badin'>Badin</option>
</select>
<input type="submit" name="Submit" value=" Go " id='jobsbycitymenubtn' onclick="return validFormDataCity();"/>
</form>
</div>
will be great thankful for your help
Since you are tagging jQuery you could use:
$('#jobsbycitymenu').on('change', function(){
$(this).closest('form').submit();
});
So your whole code (and please remove the inline script) would be:
$(function () {
$('#jobsbycitymenu').on('change', function () {
if (validFormDataCity()) $(this).closest('form').submit();
});
$('#citysearch').submit(function (e) {
e.preventDefault;
return validFormDataCity();
});
function validFormDataCity() {
if (document.getElementById("jobsbycitymenu").value == "Not Selected") {
alert("Please select a City.");
document.citysearch.jobsbycitymenu.focus();
return false;
}
return true
}
});
Demo
For plain Javascript you can use this.
I'm trying to display different buttons on selecting different field from the drop down. here's my code, it's working partialy only for the first item in the dropdown. Please advice what's wrong with my code:
<select id="my_id">
<option value="select">--Select--</option>
<option value="foo">foo</option>
<option value="bear">bear</option>
</select>
<div id="display_bt1" style="display:none;">
<input type="button" value="bt1" onclick ="" >
</div>
<div id="display_bt2" style="display:none;">
<input type="button" value="bt2" onclick ="" >
<script>
$(document).ready(function(){
$('#my_id').change(function() {
if ($(this).val() == 'foo') {
$('#display_bt2').show();
} else if ($(this).val() == 'bear'){
$('#display_bt1').show();
} else {
}
});
});
</script>
Some syntax errors, other than that, it should work:
$('#my_id').change(function() {
if (this.value == 'foo') {
$('#display_bt2').show();
} else if (this.value == 'bear') {
$('#display_bt1').show();
}
});
If you want to hide the other div on the change, add a class to each div, for example divClass, then hide that class on each change (of course this is if you want this functionality).
$('#my_id').change(function() {
$(".divClass").hide();
if (this.value == 'foo') {
$('#display_bt2').show();
} else if (this.value == 'bear') {
$('#display_bt1').show();
}
});
You can add name attribute to input element
<select id="my_id">
<option>foo</option>
<option>bear</option>
</select>
<div id="display_bt1" style="display:none;">
<input type="button" value="bt1" name="foo" onclick ="" />
</div>
<div id="display_bt2" style="display:none;">
<input type="button" value="bt2" name="bear" onclick ="" />
</div>
And then you can itterate over array of elements and compare selected option value with input's parent name attribute like this:
$(document).ready(function(){
$('#my_id').change(function() {
$this = $(this);
$('#display_bt1, #display_bt2').each(function() {
$(this).hide();
if($this.val() == $(this).children().attr('name')) $(this).show();
});
});
});
It's maybe not best way how to do it but i tried not modify HTML too much and make code more universal.
jsFiddle code