Function show and hide form elements - javascript

I am trying to create a Jquery function to add or remove a drop down menu based on the selection of a different drop down menu,
This is my very first time trying to use Java script, and i need a little help to get it going.
here is what i have done up to now, but i cant seem to get it to work can somone tell me where i have gone wrong?
$(document).ready(function(){
$(function remove() {
$("select#name").val();
if (name == "United Kindom") {
$("select.county").show();
} else {
$("select.county").hide(); });
});
<select name="ab" onchange="remove();">

Firstly, what you're using is a mash-up of Javascript and jQuery(A Javascript Library). You must understand this. Just so you know the below is jQuery, and I'll add the pure JS to the end of the post.
Try This:
$(document).ready(function(){
$(".selectWrapper").on("change", "select#ab", function(){
$("select.county").toggle($(this).val() != "United Kindom");
});
});
<div class="selectWrapper">
<select id="ab">
This is also assuming you have
<select class="country">
somewhere in your code.
//---Pure JS ----
document.getElementById("ab").onchange = function(){
var selects = document.getElementsByTagName("select"), countrySelect;
for(var x in selects){
countrySelect = (selects[x].className == "country")? select[x] : "";
}
countrySelect.style.display = (this.value == "United Kindom")? 'none' : 'block';
};

Your code contains a syntax error, undeclared variables and a scope problem.
Your code can be rewritten more efficiently: $(fn) where fn is a function is equivalent to $(document).ready(fn). Also, the .toggle method can be used instead of if-then-show-else-hide.
Fixed code
The inline handler did not work either, because function remove was defined within the $().ready function.
To fix the code itself, bind the event handler using jQuery, instead of using an inline handler:
$(function() {
$('select[name=ab]').change(function() {
var name = $("select#name").val();
$("select.county").toggle(name == "United Kindom");
});
});
//<select name="ab">
Syntax error revealed
After indenting the code properly, the syntax error can be spotted quite easily
$(document).ready(function () {
$(function remove() {
var name = $("select#name").val(); // Prefixed "var name = "
if (name == "United Kindom") {
$("select.county").show();
} else {
$("select.county").hide();
} // <----------- This one is missing!
});
});

and just a quick hint at how to make easier use of jQuery
Remember, it's the "write less, do more" library:
// Easy jquery way to run when doc loaded
$(function() {
// you dont need to include the tag in an id selector
// remember, any way you can select an element in css, you can do in jQuery
$("#Country").change(function() { // here i use the .change event to know when this select box's value has actually changed to a new value
// i'm not sure exactly what you were trying to hide and show,
// i couldn't fllow where vaiable `name` came from, but this is
// how you could easily show or hide somthing based on this select's value
var $value = $(this).val();
// although, if you're gonna have alot of possible ifs,
// i would suggest a switch statement
switch($value) {
case "United Kingdom":
// here you can choose to show a specific select for UK states/countries/ares (i'm not familiar with how it works, i'm sorry)
$("#UKStates").show();
// if you're going to show specific, prefilled select boxes,
// then it would be advised to include a classname on each one
// that you can refer to in order to hide the rest
$(".select-states").hide();
break;
case "United States":
// do work
break;
default:
// do work
}
// otherwise, if you won't have many if statements,
// just use a regular if statment, like so:
// if ($value == "United Kindom") {
// $(".county").show();
// }
// else {
// $(".county").hide();
// }
})
});
notice in my example, there is alot of commented teaching, but not alota of code. Always remember, jQuery does all the work, just do what you need too.

You could start of by reducing your function to just this, making use of the showOrHide overload of .toggle().
function remove() {
$("select[name='ab']").toggle($("select[name='ab']").val() === "United Kingdom");
}
Since you are loading jQuery, you could as well make use of its event-handling as well, instead of using inline onchange="". Something like this:
$(function(){ // Wait for DOM to be ready
$("select[name='ab']").change(remove); // Attach an change-lister
});
So the complete thing would be:
$(function(){
$("select[name='ab']").change(remove);
});
function remove() {
$("select[name='ab']").toggle($("select[name='ab']").val() === "United Kingdom"));
}

Related

Adding and Removing Required Tag Dynamically in HTML using JavaScript?

I have a select option with many values, I need to toggle a field required or not based on the select option value, tried all possible solutions such as:
$(document).ready(function () {
});
function toggleFields(sel) {
var valuee = sel.value;
alert (valuee);
if (valuee < 7){
//$("#comment").setAttribute("required","");
alert("Removed");
$('#comment').required = false; //Correct
$('#comment').removeAttribute("required"); //Correct
}
else{
$('#comment').required = true; //Correct
$('#comment').setAttribute("required", "");
alert("Set");
}
}
a running example can be found into this fiddle
Fiddle Link is below
Your jQuery code should be inside $(document).ready(function () { /*your code here */ } not under it.
EDIT: or it should be set up to not call any jquery code before jquery is loaded. You may want to remove the inline function and set up an event handler inside your script
Also, what is $('comment')? It should be a selector eg. $('#comment') or an element eg. $('div').
EDIT: https://jsfiddle.net/tjwoo1y7/11/
$('#comment').attr("required", false);
$('#comment').attr("required", true);

Checking value of an html select with jQuery

I have the following select box:
<select id="choose">
<option value=1>A</option>
<option value=2>B</option>
<option value=3>C</option>
</select>
<div id="hide-me">hide me!</div>
How can I hide an element when I select option "B"? I tried this:
<script type="text/javascript">
if ("#chose option:selected").val(2) {
$("#hide-me").hide();
};
</script>
I think I'm close, but nothing happens when I select option "B". Anyone have any suggestions?
You need to attach change event to select element to detect the option change. then use .toggle() with argument value not equal to 2 for making show/hide decision :
$('#choose').change(function(){
$("#hide-me").toggle($(this).val() != "2");
})
Working Demo
Listen to the change event of the #choose element, and add your conditional logic there.
Example Here
$('#choose').on('change', function () {
if (this.value === "2") {
$("#hide-me").hide();
} else {
$("#hide-me").show();
}
});
..equivalent, but perhaps less readable version:
Example Here
$('#choose').on('change', function () {
$("#hide-me").toggle(this.value !== "2");
});
As a side note, the value of the selected option is a string.
If you wanted to, you could also convert it to a number:
if (parseInt(this.value, 10) === 2) { ... }
or you could use == rather than ===: (not suggested, though. This could lead to logical errors.)
if (this.value == 2) { ... }
Without jQuery:
Example Here
document.querySelector('#choose').addEventListener('change', function () {
var element = document.getElementById('hide-me');
if (this.value === "2") {
element.style.display = 'none';
} else {
element.style.display = 'block';
}
});
The problem with your code is that:
It is not syntactilally correct — ("#chose option:selected").val(2) is an expression, which in turn should be wrapped in parentheses to be a proper condition for if, like this:
if (("#chose option:selected").val(2)) {
However, even after that your code is not correct because you're not actually using jQuery. You're calling method .val() just on a string "#chose option:selected", whereas that string should instead be a jQuery selector passed to jQuery itself:
if ($("#chose option:selected").val(2)) { // $ is the jQuery object that does all the work
However2, even that is incorrect, because you'd just be checking the value of an element right away. What you need is to wait for an element to be changed. Other answers explain very well how to do that.

How can I make an element appear and disappear using Jquery.

I want to do something like this:
$(document).ready(function(){
if($('.undermenu').css('display','block')){
$('#menu').click(function(){
$('.undermenu').css('display','none');
});
}
else{
$('#menu').click(function(){
$('.undermenu').css('display','block');
});
}
});
This code does not work, but is there any Jquery "effect" or whatever that I can use to hide/un-hide.
For example is there and way to check whether or not display is set to none or block?
Thanks.
Just use toggle():
$('#menu').click(function() {
$('.undermenu').toggle();
});
Though the reason your if($('.undermenu').css('display','block')) didn't work is because you set the display property of the element(s) to block, rather than getting the display property and testing it, which would be:
if ($('.undermenu').css('display') =='block')
If you really want to use an if to test the current display, before modifying the presentation, you'd have to do it inside of the click handler (otherwise it will only run once, on DOMReady, rather than every time):
$('#menu').click(function(){
if ($('.undermenu').css('display') == 'block') {
$('.undermenu').hide();
}
else {
$('.undermenu').show();
}
});
Or, if you want to risk the wrath of your colleagues, you can jazz that up a little:
$('#menu').click(function(){
var undermenu = $('.undermenu');
undermenu[undermenu.css('display') == 'block' ? 'hide' : 'show']();
});
References:
css().
toggle().
You use a setter on your condition :
// This line update .undermenu to display it and return true (return $('.undermenu'), so true)
if($('.undermenu').css('display','block')){
But you must get the value, and test
if($('.undermenu').css('display') === 'block'){
And you code conception is bad. If you do that, you test on document are ready if the .undermenu are displayed or not, and you put a function to the click trigger (to display or to hide..) but ! when your .undermenu was change, you already have the same trigger (to display or hide, and he never change)..
So you need to put your trigger for each click and test the value (displayed or not) on the trigger :
$(document).ready(function(){
$('#menu').click(function(){
if($('.undermenu').css('display') === 'block'){
$('.undermenu').hide();
}
else {
$('.undermenu').show();
}
});
});
On jquery exists:
$("#element_id").show();
$("#element_id").hide();
also you can use:
$("#element_id").fadeIn();
$("#element_id").fadeOut();
This show and hide elements with fade effects.
You can query if the element is hidden:
if($("#element_id").is(":hidden")){
$("#element_id").show():
}
else{
$("#element_id").hide();
}
What you're looking for is .toggle()
$("div").click(function () {
$("img").toggle("slow", function () {
// Animation complete.
});
});
Here is a fiddle: http://jsfiddle.net/FQj89/
You can put the if statement in the function so you don't repeat yourself. You can probably also use toggle(); type stuff depending on what you are doing. ---
$('#menu').click(function(){
if ( $('.undermenu').is(':visible') ) {
$('.undermenu').hide();
else {
$('.undermenu').show();
}
});
This is a good way too, depending on what you are doing though, one may be better than the other.
if ( $('.undermenu').css('display') === 'block' ) { // do something }

CasperJS fails to set select list values

I've got a select list that looks like this:
<select id="ListingType" name="Criteria/ListingTypeID" onchange="Search.toggleListingType(this);">
<option selected="selected" value="1">RH1</option>
<option value="2">BC4</option>
<option value="3">RR3</option>
<option value="4">RH2</option>
<option value="5">RE0</option>
</select>
I'm trying to set the value to 3. I've unsuccessfully tried 3 ways to do this.
1.
this.evaluate(function(value) {
document.querySelector('select#ListingType').value = value;
return true;
}, '3');
// insure the onChange JS is run
this.evaluate(function() {
var element = document.querySelector('select#ListingType');
var evt = document.createEvent('HTMLEvents');
evt.initEvent('change', false, true);
element.dispatchEvent(evt);
});
This appears to work (throws no errors), but the value doesn't get changed.
2.
this.fillSelectors('select#ListingType', {
'select[name="Criteria/ListingTypeID"]' : "3"
}, true);
This throws the error message: ``CasperError: Errors encountered while filling form: no field matching css selector "select[name="Criteria/ListingTypeID"]" in form''
What's wrong with my selector?
3.
// In desperation...
this.sendKeys('select#ListingType', 'RR3');
This also seems to work (no errors), but again the value is unchanged.
Just for completeness, I've tried sending the "change" event after each of the variations. I also dump out the attributes of the selected element after each, and it never shows the value as being set.
Note the page that this selector is on has a ton of JS code on it, and this <select> element is not wrapped in a <form> element.
I'm sure I'm making some really stupid mistake, but after hacking on this code for the last several days, I've not made any progress. What's a working way to do this?
You can use slimerJS (it opens firefox) to easily check a change in value.
this.fillSelectors('form#id_form', {
'select[name="Criteria/ListingTypeID"]' : "3"
}, false);
this.wait(6000,function(){
this.echo("i saw my new value");
});
And if you want to fill the option by its text and not value (i find it easier): use this function :
casper.fillSelectOptionByText = function (selectSelector,text){
this.evaluate(function(sel,setByText) {
$(sel + " > option").each(function() {
if($(this).text() === setByText) {
$(this).attr('selected', 'selected');
}
});
},selectSelector,text);
};
And in your test :
this.fillSelectOptionByText("select[name='year of birth']","1991");
The page has to have jquery of course, or you inject it.

Trying to dynamically validate fields with jQuery - custom function

I'm working on a validation function in jQuery and am getting a bit stuck. I've got a working version that is very lengthy and full of hardcoded form values which I'm trying to avoid. Here's what works, currently:
$(document).ready(function(){
var fname = $("#formFName");
var lname = $("#formLName");
fname.blur(validateFName);
lname.blur(validateLName);
function validateFName(){
if(fname.val().length > 0){
fname.removeClass("req_error");
return true;
}
else {
fname.addClass("req_error");
return false;
}
}
function validateLName(){
if(lname.val().length > 0){
lname.removeClass("req_error");
return true;
}
else {
lname.addClass("req_error");
return false;
}
}
});
That part works fine for those two fields but I'd like to encapsulate the whole thing in a function that's a bit easier to maintain. Something like this:
$(document).ready(function(){
$("#first_name").blur(validateField("first_name","text"));
$("#last_name").blur(validateField("last_name","text"));
$("#email_address").blur(validateField("email_address","email"));
function validateField(formfield, type){
var field = $("#" + formfield);
switch(type) {
case "text":
if(field.val().length > 0){
field.removeClass("req_error");
return true;
}
else {
field.addClass("req_error");
return false;
}
break;
case "email":
var filter = /^[a-zA-Z0-9]+[a-zA-Z0-9_.-]+[a-zA-Z0-9_-]+#[a-zA-Z0-9]+[a-zA-Z0-9.-]+[a-zA-Z0-9]+.[a-z]{2,4}$/;
if(filter.test(field.val())) {
field.removeClass("req_error");
return true;
else {
field.addClass("req_error");
return false;
}
break;
}
}
});
However, when I do that I get the following error in Firefox's JS error log:
Error: ((f.event.special[r.origType] || {}).handle || r.handler).apply is not a function
Source File: /scripts/jquery-1.7.1.min.js
Line: 3
A quick Google for that error hasn't yielded anything that means anything to me, unfortunately. I've tried alerts in various spots and doing so has verified that the proper form field names are indeed being passed where there supposed to be, but as I'm fairly new to jQuery (and not great at JavaScript) I'm at a bit of a loss here.
Thanks to anyone who can point me in the right direction. Also, if anyone thinks that I'm going about this in the wrong way, I'm more than happy to change. I tried using the jQuery validation plugin but I'm also using some dynamically created fields and unfortunately the plugin prevents the visitor from submitting the form when hidden required fields are involved.
Sounds like you could simplify this by attaching behavior instead of specific elements:
<input type="text" id="someId" class="validate-text" />
<input type="text" id="someOtherId" class="validate-email" />
$('.validate-text').live('blur', function()
{
$(this).removeClass('req_error');
if($.trim(this.value).length < 1)
$(this).addClass('req_error');
});
$('.validate-email').live('blur', function()
{
// Same thing with the email validation logic
});
This way, you dont need to attach specific event handlers to your elements and instead use those handlers to check the behavior you want. Then you simply mark HTML elements with specific classes to mark the validation mode you want.
Assuming I understood your question correctly.
You can't pass a function invocation expression to .blur(). You can pass an anonymous function constructor:
$("#first_name").blur(function () {validateField("first_name","text");});
Or pass the name of a function:
function validateFirstName() {
validateField("first_name","text");
}
* * *
$("#first_name").blur(validateFirstName));
#Tejs's suggestion to use classes to attach validators is a good one, as well.

Categories

Resources