Dropdown javascript / jquery form validation debugging help needed - javascript

I have the following jsfiddle setup:
http://jsfiddle.net/xCCA2/
Basically when a the form is submitted, the size select dropdown is validated to make sure a selection has been made. If a valid size has been selected then the form is posted.
If an invalid selection is made, then an alert box "An invalid size has been selected" should popup.
Please can I get help debugging this.
Nb: there will be many forms on a page, and would prefer to uses classes rather than id's also there is some commented out html, where the form has been set a class, this works but anything within the form becomes clickable, which I do not want. Only the button should trigger the validation.
Thanks

try this
$(".wq").live( "click", function () {
alert("test");
if($("select").val()!="")
alert("not empty");
else{
alert("select a val");
return false;
}
// $(this).submit();
});
http://jsfiddle.net/xCCA2/4/

Look here
http://bassistance.de/jquery-plugins/jquery-plugin-validation/
Add
<script type="text/javascript"
src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.8.1/jquery.validate.min.js"></script>
and required to the select
<select required
DEMO HERE

Related

validate error message not displaying for drop down list when not selected

Please bear with me as I am not sure what I have done wrong here:
Basically I have a form and I have some drop down lists.
If I hard code the select list for my drop down list with styleClass="requiredinpfield" then I will get a proper validation error message pops up below the select list whenever I don't select an option from the list and if I try hit submit button.
However, because some of the drop down lists are not always required (they only required when certain option was selected) so in this case I am not hard coding these select lists to have styleClass="requiredinpfield" but instead I am using jQuery to dynamically add the requiredinpfield class to the list object whenever an associate radio button was selected.
The problem I am having now is this won't show the validation error message when I don't select any option and try to hit the Submit button. It prevent me from continue, however. Its just I don't get to see the error message. Can you see what I have done wrong?
Here is an example of how I use jQuery to add the requiredinpfield class and it is not showing me the validation error message when needed:
HTML
<div id="fruitDivId">
<apex:inputField id="testPickList" value="{!PickTheFruitYouLike__c}" styleClass="selectpicker"/>
</div>
A radio button to confirm that the list is needed
<apex:selectRadio value="{!DoYouLikeFruit}" onchange="whenAnOptionWasSelectedAndINeedToAddRequiredInpField(this.value,'fruitDivId');" styleClass="requiredinpfield radio pa-cus pa-cus-other">
Script to add requiredinpfield class
function whenAnOptionWasSelectedAndINeedToAddRequiredInpField(t,divId)
{
if (t == 'Yes' ){
$('[id$='+divId+']').show();
$('[id$="testPickList"]').addClass('requiredinpfield');
}
else{
$('[id$='+divId+']').hide();
$('[id$="testPickList"]').removeClass('requiredinpfield');
}
}
Script to validate
Note: my submit button will trigger the !checkRequired() method.
function checkRequired(){
var isValidate = true;
//$('.errorIcon').css('opacity', '0');
$('.requiredinpfield').each(function(){
if($(this).is("select") && $(this).val() == ''){
/*alert("Hello!!");*/
if(!($(this).next('.requiredinpfield').first().next('.errorMsg').size()>0)){
console.log($(this).next('.requiredinpfield'));
$(this).next('.requiredinpfield').first().after('<div class="errorMsg"><strong></strong> You must select an option</div>');
}
isValidate = false;
}
else{
if($(this).is("select") && (($(this).next('.requiredinpfield').first().next('.errorMsg').size()>0)))
{
$(this).next('.requiredinpfield').first().next('.errorMsg').remove();
}
}
});
//alert(isValidate);
return isValidate;
}
Assuming that the rest of the code is correct, the problem might in the way you are selecting elements by ID
in jQuery, to select an element by id simply write
$('#idoftheelement')
so in your whenAnOptionWasSelectedAndINeedToAddRequiredInpField function,
try replacing
$('[id$='+divId+']')
with
$('#'+divId)
do the same at all locations where you are selecting by id.

Radio button REQUIRED if input field has content

I have a a reasonably quick problem to solve (I think). I have a form online and it validates the required content for the user's data, but has no validation on the first part of the form.
I've been asked however if I can make a radio button REQUIRED depending on whether an input field has been filled in.
The form can be found here:
http://www.elcorteingles.pt/reservas/livros_escolares/form.asp
So if the person start's filling in the input fields on the first line, that the radio buttons in the group become REQUIRED (for either the CDROM ou CADERNO but not both)
You can handle the focusout and blur events for the input:
$(function () {
// Handle every input type text.
// To select specific inputs, give them a common class and change the
// selector accordingly.
$("input[type=text]").on("focusout blur", function () {
// Check for inputs with class radio_btns which are in
// the parent element (li).
// Set their required property.
$(this).parent().find("input.radio_btns")
.prop("required", $(this).val().trim().length > 0);
});
});
Demo
jQuery reference (Tree Traversal)
jQuery reference (.prop())
jQuery reference (.focusout())
jQuery reference (.blur())
This will work. You can include the following JQuery code in the script tag, and also the JQuery cdn link in the head tag.
$(document).ready(function(){
$('#01titulo').focusout(function(){
if ($(this).val() !== "") {
$('[name="01caderno"]').prop('required', true);
} else {
$('[name="01caderno"]').prop('required', false);
}
alert($('[name="01caderno"]').attr('required'));
});
});
Try using the following js code its working:
$(document).ready(function(){
$(".titulo_books").each(function(){
$(this).focus(function(){
var radioChecked=0;
var currElemId = parseInt($(this).attr('id'));
var radioSelecterId = (currElemId>9) ? currElemId : "0"+currElemId;
$("input:radio[name="+radioSelecterId+"caderno]").each(function(){
if(radioChecked==0)
{
radioChecked==1;
$(this).attr("checked","checked");
}
});
});
});
});
I have checked it by executing this from console on your site and it seems to work fine. You can alter this in the way you want. I have checked one of the four available radio button. User can change the input value if required. Or you can also change the default radio button selected through my code.

JavaScript hide element function

I have a form where the user can select a generic auto-population based on checking a radio button. When the user checks the auto-populate radio button, the fields are auto populated with the data and then the fields become disabled.
In this first part of the function, I pass the auto-filled data:
$('#myOptions').click(function()
$('#value1').val("Auto-filled data");
$('#Value2').val("Auto-filled data");
$('#Value3').val("Auto-filled data");
In this second part, I am disabling the html inputs
// now i am disabling the html inputs:
$('#Value4').prop("disabled", true);
$('#Value5').prop("disabled", true);
$('#value6').prop("disabled", true);
Suppose I have another field with an ID of "Value7" in the form, that I would like to hide from the user interface as part of this function.
How can I hide the "Value7" input upon function triggering? I appreciate the help, I am very new to JavaScript, though I find it very exciting!
Using jquery:
To hide
jQuery('#Value7').hide() or jQuery('#Value7').css("display","none")
To show the element back
jQuery('#Value7').show() or jQuery('#Value7').css("display","block")
or pure js:
javascript hide/show element
Try this javascript:
if you want disable:
document.getElementById('#Value7').setAttribute("disabled","disabled");
if you want enable:
document.getElementById('#Value7').removeAttribute('disabled');
if you want to hide :
document.getElementById('#Value7').css("display","none");
if you want to show:
document.getElementById('#Value7').css("display","block");
I am not getting what are you trying to ask actualy .
Let me know if this helps -
$("Value7").hide()

Form onsubmit issue with javascript

Ok so I am really confused on this whole javascript in HTML stuff.
What I am trying to do is validate a form either "onblur" or on submit with an external file.
Here is the HTML code that works for the first field:
<script>
function notEmpty(rep, errMsg)
{
var errMsg = "Please enter something in Rep";
var rep = document.getElementById('submitted_by_hrrep');
if(rep.value == '')
{
alert(errMsg);
hrrep.focus();
return false;
}
return true;
}
</script>
This is in the body of the form near its field.
<script type="text/javascript">document.getElementById("submitted_by_rep").onblur=notEmpty;</script>
So that DOES work and will pop an alert that tells em to go back
What I CAN'T get to work is doing this for the rest (15 fields) of the form.
The "onsubmit" is confusing me and I think it's right but I am not sure.
<form onsubmit="return formValidation()" method="post" action="process.asp" >
Anything will help
EDIT
function validate()
{
if(document.newempRequest.submitted_by_hrrep.value ==='')
{
alert("Please provide your name");
document.newempRequest.submitted_by_hrrep.focus();
return false;
}
I got so frustrated that I started from scratch and took it a field at a time. Found that this works for the fields that need text, it looks messy for the file but calling it externally works flawlessly.
I wish I could use jquery but it seems to be more complex to setup that I actually need. Thanks for the help :)
You would have to grab all the inputs then iterate over them with a loop of some flavor, maybe a for loop?
with jquery it's really easy since there are already form validator plugins out there, and the selectors are really friendly. Using jquery,
$('#formId input')
would grab all the inputs in the form, then you can use a .each() to iterate through all the inputs
You obviously aren't going to be able to .focus() on all of the fields though, so need another function to handle the entire list instead of just one.

Retrieving value of form fields in Jquery

I have a form field in html that goes along the lines of:
<form id="tasklist">
<input type="text" id="name" ...></input>
... more form elements here ...
</form>
Now in my jQuery code, I would like to get the value of these form elements, but I am unable to see what I'm doing wrong with the following code:
$(document).ready(function(){
$("#tasklist").submit(function(){
alert($("#name").val()); // This does not alert anything on form submit
});
});
I have made sure all of my html id's are unique, the javascript code is placed at the bottom of the document, in script tags and any other alert placed there works (i.e. alert("hello world"); place before the submit method.
I have seen a few other questions like this on stackoverflow, i.e. (Jquery form field value and Retrieving the Value of an input text field in Jquery) but they do not seem to solve my problem.
Any ideas?
When a form is submitted, the page reloads. You need to prevent that!
$(document).ready(function(){
$("#tasklist").on('submit', function(e){
e.preventDefault();
alert( $("#name").val() );
});
});
And close the functions properly!
You have some typos : the functions are not closed. It cause JS errors and could stop the script execution.
Try :
$(document).ready(function(){
$("#tasklist").submit(function(){
alert($("#name").val()); // This does not alert anything on form submit
});
});
Update
Basic fiddle exemple : http://jsfiddle.net/UQTY2/28/

Categories