dynamic changing element style using JS - Joomla ChronoForms - javascript

Please help me with a form I'm trying to do.
I have a dropdown select, all the options in the < select > have ID's, for example: one option has id="hide_me", other option has id="hide_none".
Here is the JS that I have for the form:
<?php
$script = "window.addEvent('domready', function() {
$('recipe').addEvent('change', function(event) {
if ( $('recipe')document.getElementById('hide_it').selected === true ) {
$('hide_me1').setStyle('opacity', '1');
$('hide_me2').setStyle('opacity', '1');
}
});
$('recipe').addEvent('change', function(event) {
if ( $('recipe')document.getElementById('hide_none').selected === true ) {
$('hide_me1').setStyle('opacity', '0');
$('hide_me2').setStyle('opacity', '0');
}
});
});
";
$doc =&JFactory::getDocument();
$doc->addScriptDeclaration( $script );
?>
"recipe" is the name and ID of the dropdown < select >
At the moment it's giving me a JS error like "SyntaxError: Unexpected identifier", could somebody help me please with this

your generated js looks like this:
window.addEvent('domready', function() {
$('recipe').addEvent('change', function(event) {
if ($('recipe') document.getElementById('hide_it').selected === true) {
$('hide_me1').setStyle('opacity', '1');
$('hide_me2').setStyle('opacity', '1');
}
});
$('recipe').addEvent('change', function(event) {
if ($('recipe') document.getElementById('hide_none').selected === true) {
$('hide_me1').setStyle('opacity', '0');
$('hide_me2').setStyle('opacity', '0');
}
});
});
if you use something like jslint / jshint or even paste in jsfiddle and press the jslint button, it will immediately report the problems.
however:
$('recipe') document.getElementById('hide_it').selected === true) makes no sense. I guess you are trying to read the option with id hide_it that is a child of recipe?
its the wrong thing to do but this would be something like:
$('recipe').getElement('#hide_it').get('selected'); // pointless as by id alone is faster and id is meant to be unique
document.getElement('#receipe #hide_id').get('selected'); // also pointless like above, alt syntax that allows you to combine selectors.
$('hide_it').get('selected'); // works but also wrong, not how you work with selects.
The correct way to obtain the value of a select with mootools will be simply:
$('receip').addEvent('change', function(){
// within this function, this === $('recipe');
var opacity = this.get('value') === 'hide_it' ? 1 : 0;
$$('#hide_me1,#hide_me2').setStyle('opacity', opacity);
// w/o a reference you could do in a single line:
$$('#hide_me1,#hide_me2').setStyle('opacity', +(this.get('value') == 'hide_it'));
});
this is still somewhat ineffective as it will lookup the 2 hide_me els every change event when they are probably static.
you should also stop using ids and pattern this based around classes, ids does not scale well.

Related

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.

Jquery - wrapping a bind function to THIS elements

I have multiple tables on a page (there will be over 100) and I want to use one function for all of them. When the user selects "Custom" in the drop-down menu, additional questions apply TO ALL OF THEM. How do I wrap my function in a THIS statement to have it only added to that individual table. I apologize in advance for my description of the issue.
$(document).ready(function(){
$('td.additional_content').css('visibility', 'hidden');
$('#srds_mapping').bind('change', function (e) {
if( $('#srds_mapping').val() == 'Custom') {
$('td.additional_content').css('visibility', 'visible');
$('td.additional_content .custom').show();
} else {
$('td.additional_content').css('visibility', 'hidden');
$('td.additional_content .custom').hide();
}
}).trigger('change');
});
It is better explained by looking at it
http://jsfiddle.net/2Q7J7/2/
this is the targetted element inside the event handler:
$('#srds_mapping').bind('change', function (e) {
if( $(this).val() == 'Custom') { // traverse to find the target input element
Note that you should not use more than one ID on the page. Use classes or other selectors instead, f.ex:
$('select').bind('change', function (e) {
if( $(this).val() == 'Custom') {
jQuery .each() function would be a good option:
Assuming $('#srds_mapping') is your table. Firstly, instead of id you could add a class to the tables. For example <table id="srds_mapping" class="srds_mapping"></table>. After that is in place you could do something like this.
$('.srds_mapping').each(function(){
$(this).bind('change', function (e) {
// other function stuff
}).trigger('change');
});
Also, this thread may be worth a read, or something to think about.

Function show and hide form elements

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"));
}

Using change(); twice for same div causing problems

UPDATE** This is probably too much code. But... heres the situation. I have a search at the top of the page. I use some fancy jQuery so when you click on a select option(#categoris) a new select option(#type) appears next to it. Now, I have another change event. On keyup of any text field or change of any select, an ajax search is fired. This works on everything but #type. #type is the select option that pops out from #categories on change(); So, I need change to work on #type. Here's the code pop out the #type select option. You can just skim. Code works fine...
$(document).ready(function() {
$('#category').change(function() {
var category = $('#category').val();
//CATEGORIES...
// any_type / NULL
var any_category = '<div id="type_holder_line"></div>';
// Music
var music = '<div id="type_text">Type</div><img src="app/search/images/arrow.gif" id="arrow" /><select name="music_type" id="type"><option value="any_style" selected="selected">Any Style</option><option value="Jazz">Jazz</option><option value="Rock">Rock</option></select>';
// Restaurants
var restaurant = '<div id="type_text">Type</div><img src="app/search/images/arrow.gif" id="arrow" /><select name="restaurant_type" id="type"><option value="Japanese">Japanese</option><option value="Mexican">Mexican</option></select>';
if($(this).val() == 'Any Category') {
$('#type_holder').html(any_category);
}
if($(this).val() == 'music_page') {
$('#type_holder').html(music);
}
if($(this).val() == 'restaurant_page') {
$('#type_holder').html(restaurant);
}
});
Here, is the change();. #type should instantiate the search on change(); But, doesn't either because it's made from #categories on change();. Or, because I'm using change(); twice.
// *** START *** keyup / change (for select option)
$('#loc, #dist, #category, #type, #search_title').bind('keyup change', // HERE, #type is ignored because it's created from #categories on change(); function() {
var loc = $('#loc').val();
var dist = $('#dist').val();
var category = $('#category').val();
var type = $('#type').val();
var search_title = $('#search_title').val();
if(loc == '' && search_title != '') {
$.post('http://localhost/app/search/page_type/music_spot/search.name.php', {
category:category,
type:type,
search_title:search_title
},
function(data) {
$('#front_left').html(data);
});
}
});
});
I think you should try the live() function. Because the live function handle the dynamically created elements but you can read more on documentation :)
So you can try something like this:
$('#loc, #dist, #category, #type, #search_title').live('keyup change', function(){
// code here
});
Please read the manual because I see now that the .live() function is deprecated for jquery 1.7, and choose the appropiate function for your jquery version.
I hope this resolve your problem, and sorry for my english :">

jquery validate: adding a required rule with custom message based on wether a different form field has a value

I know this seems like a repeat question, but i've read all the others and they arn't quite the same :(
I've got some drop downs, and if they have something other then an option with a value of "0" selected then I want the coresponding Expiry Date field to be required.
I tried putting the rule in the class of the objects, and using the rules('add') function. Here's where i am at right now:
$('[id^=ExpiryDate]').each(function() {
$(this).rules('add',
{ required: function() {
if ($('#q' + id).val() == '0') {
return false;
}
else {
return true;
}
}
}
);
my expiry date fields are id'ed like "ExpiryDate1", "ExpiryDate2" and the corresponding drop downs are ided like "q1" and "q2".
this makes my scripts fail. it doesn't give any errors in the error console or firebug. but it doesn't execute any javascript that occurs after it either.
I have a feeling it's something really obvious and stupid that i am missing. but i've been staring at this code for a couple hours now and can't find it!
Thanks in advance!
Try this:
$('[id^=ExpiryDate]').each(function() {
var id = $(this).attr('id').replace('ExpiryDate','');
$(this).rules('add', {
required: function() {
return $('#q' + id).val() !== '0';
}
}
);
Currently, your id is undefined, so it's just not finding any elements. The rest is just a shorter version.

Categories

Resources