jQuery validation plugin - removing elements - javascript

I'm using the jQuery validation plugin. On most of my input type... tags I have class='required'.
When I submit the page, via JavaScript, the controls on the page that have this class are found. However, there are a handful of checkboxes that I don't need to validate.
I've tried removing the class code completely from the input tag, also tried class='cancel', and class='required:false.
When doing any of those things though when the form submits it can't find the checkbox control.
How do I still keep the ability to do Request.Form and find my checkbox object but at the same time when the form submits don't apply validation to this particular control.
Thank you.
Edit here.
This is what I'm using without the "checked" code and ternary operator. In my input tag I'm calling a function like this...
sb.Append(" <td><input type='checkbox' id='chkFlashedCarton' name='chkFlashedCarton' " + strDisabled + " value='true' " + GetPackagingSizeTypeControlValue("chkFlashedCarton") + " />" + crlf);
Inside that function is where I check for the True or False coming back, like this.
case "chkFlashedCarton":
strResultValue = pst.FlashedCarton.ToString();
if (strResultValue == "True")
{
strResultValue = " checked";
}
break;
strResultValue is what is returned back.
Does this help to see? Thank you.

I don't think the checkbox not appearing is related to the validation issue. By default, inputs without values are not posted back with the form. One way around that for checkboxes is to have an hidden form field per checkbox that sets the opposite value with the same name as the checkbox. When the form is posted back with the checkbox checked, you'll get both values. If the checkbox isn't checked, you'll get the default value (from the hidden field). Thus, you only need to check if the value for the checkbox contains the non-default value and act appropriately on the server side.
<input type='checkbox' name='cb1' value='true' /> Check Me
<input type='hidden' name='cb1' value='false' />
You can then omit the required class and be assured that you will always get some value for the checkbox.
On the server side, then you do something like:
bool cb1Flag = false;
if (Request.Form["cb1"].ToUpper().Contains("TRUE"))
{
cb1Flag = true;
}
Edit (based on your edit)
Try this:
sb.Append(" <td><input type='checkbox' id='chkFlashedCarton' name='chkFlashedCarton' " + strDisabled + " value='true' " );
if (pst.FlashedCarton)
{
sb.Append( " checked='checked'" );
}
sb.Append( " />" + crlf);

Related

Returning the label value of a radio button using javascript/jQuery

I've recently started learning jQuery and for the first time after weeks, I didn't manage to find an answer to my problem on this site which leads me to think I've screwed when creating my radio buttons.
A little breakdown of what I do: I have this simple web page which contains a div:
<div id="skins">
</div>
In this div, I will push radio buttons that are generated by going through a for loop and assigning to each one of them a text which is stored in an array named skins
for(var i in skins) {
$("#skins").append("<input type='radio' class='result_skin' name='skin'>" + skins[i].name + "</br>")
}
I add a break at end of each radio button so they will sit one on top of each other and not be generated one after another (so it looks like a list)
Then I want to check which radio button has been checked and return its label text which after research, it can be done this way:
$("#skins").click(function() {
$("input:radio:checked").each(function() {
var text = $(this).text()
console.log(text)
})
})
This is where the problem is. The variable text in this case is returned as an empty string which leads me to thing that the way I created a radio button is incorrect.
Could someone help me with this small issue?
Radio buttons do not have text. Only elements that can encapsulate content between their opening and closing tags can have text and radio buttons don't get a closing tag, so they can never "contain" anything, let alone text. Instead, they have a value and that's where their data and ultimate meaning resides, not from the text caption (what you are calling label) that is next to them says.
So, really you need to give each of your radio buttons a value and then you can get that value with:
$(this).val()
not:
$(this).text()
Try this:
var skinValues = ["one","two","three","four","five", "Champion zed"];
// Don't use for/in loops with arrays, use .forEach()
skinValues.forEach(function(skin){
// each radio buttons needs a unique value and that's where its data is stored
$("#skins").append("<input type='radio' class='result_skin' name='skin' value='" + skin + "'>" + skin + "</br>")
});
$("#skins").click(function(){
$("input:radio:checked").each(function(){
var text = $(this).val() // Radio buttons don't have text, they have a value
console.log(text)
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="skins"></div>
The basic use of radio buttons is the fact that you can force people to pick one out of many choices. To achieve this effect you will have to use the same name attribute on the radio buttons you want to group together.
To find out what radio button someone has selected, you can then indeed check with jQuery using the following code:
$('input[name=radioName]:checked', '#myForm')
with '#myForm' being optional, if you want to search in a certain form.
The text you write next to an input is totally unassociated with it. To get the value of the input you should add a value attribute, or another data attribute. More information about data attributes can be found here.
Piecing all this information together, your code should look something like this:
Creating the skin list
for(var i in skins){
$("#skins").append("<input type='radio' class='result_skin' name='skin' value='" + skins[i].name + "'>" + skins[i].name + "</br>")
}
Accessing "the text" next to the input
var text = $('input[name=skin]:checked').val();
Since you use values for the radio buttons, try not using .text() but .val() instead
The text associated to the radio isn't linked to the input tag. So you have to wrap the text and the input into a parent tag (something like a div):
<div>
<input type="checkbox"/>
<span class="label">Text</span>
</div>
When you want to check the text
$("input:radio:checked").each(function(){
var text = $(this).parent().find( "span" ).text()
console.log(text)
})
Updated with JiFus updated idea
You can use data-attribute or value attribute
for(var i in skins){
$("#skins").append("<input type='radio' class='result_skin' name='skin' data-skin-name='" + skins[i].name + "'>" + skins[i].name + "</br>")
}
And call it with dataset
$("input:radio:checked").each(function(){
var text = $(this).dataset['skin-name']
console.log(text)
})

How to validate JQuery forms that have multiple name[] arrays?

These fields are created with JQuery.
How do I validate the array of "aname[]" fields (you have to fill them in before going to the next step)?
JQuery to HTML:
input ="<input name='aname[]' id='1' placeholder='yourname1' type='text' required />";
input +="<input name='aname[]' id='2' placeholder='yourname2' type='text' required />";
input +="<input name='aname[]' id='3' placeholder='yourname3' type='text' required />";
$(".placeholder").append(input);
JQuery command to try and get input
$(document).ready(function() {
var items = $('input[name="items[]"]').text();
if(items == ""){
alert("fill this field");
}
});
Two issues:
text() retrieves the text of an element (like a span or div), not the value of an input. To get the value of an input, use val. (Or if just working with the DOM element, the value property.)
You need to run the check in response to an event, not just on page load.
If you change text() to val() in that code, you'll only be checking the value of the first one (text() is a bit odd and works differently to val() and most other jQuery getters).
So if you want to check that all of them are filled in, you'll need an event handler and a loop of some kind:
$(document).ready(function() {
$("selector-for-the-form").on("submit", function(e) {
$(this).find('input[name="items[]"]').each(function() {
if (this.value == "") {
this.focus(); // So the user knows which field...
alert("fill this field"); // ...although this may mess that up
e.preventDefault(); // Prevent form submission
return false; // Stop looping
}
});
});
});
Of course, alert isn't usually the greatest user experience for this sort of thing. It's usually more pleasant if you do proactive validation and a notification that doesn't jar the user and interrupt what they're doing until you have to (like changing the color of the border of the input and/or showing an inline message). (There are also lots of plugins available to help you with doing that.)

jQuery table and storing values issue

So I'm working on a JS project for school where I have a form in which the user enters the amount of forces in a problem, once entered a loop will created new fields per force. I have that part down, but I am having an issue with storing the text input from each of these new fields. I am using the .on function where the user has to click a button and then based on the id of the button clicked a number for the force array is created. The input is then suppose to be read into the array, but its just not working and its driving me nuts. Any ideas? Thanks in advance.
function forceRecording(numofforces){
for(var i =0; i<numofforces; i++){
$('#button1').after("<tr><td>Force DFO " + i +":</td><td><form><input type='text' name='lengthMeasure_'/></form></td><td><div class='button' id='lengthButton_"+i+"'>Add!</div></td></tr>")
$('#button2').after("<tr><td>Force " + i +":</td><td><form><input type='text' name='forceMeasure_'/></form></td><td><div class='button' id='forceButton_"+i+"'>Add!</div></td></tr>")
}
};
$("button[id^='forceButton']").on("click",function(){
var num = parseInt($(this).attr("id").split("_")[1]);
forces[num] = $('input[id=forceMeasure_'+num+']').val();
$('#button1').after('<td>'+forces[num]+'</td>');
});
As you can see I'm adding another column in my table temporarily just to check if the force is actually point into the array but when I run this, nothing new pops up.
I am pretty sure you would have solved this issue by now. But I just happened to come across this post and thought that an answer could help future readers.
There were three issues in your code which prevented it from working and they are as follows:
$("button[id^='forceButton']") is used instead of $(".button[id^='forceButton']"). Note the . before button. Without the . jQuery would look for a button tag with id like forceButton whereas the tag in question was a div with class as button.
$('input[id=forceMeasure_'+num+']').val(); is used to get the text box value but your input field doesn't have any id. It only has a name, so instead use $('input[name=forceMeasure_' + num + ']').val();.
The input field is set as <input type='text' name='forceMeasure_'/>. Note that the count part after the forceMeasure_ is missing. It should have been <input type='text' name='forceMeasure_" + i + "'/>.
Making all the three changes as mentioned above, the code works fine.
Click here for a sample demo of the working code.

changing value of hidden input fields depending on submit button

I have multiple forms in my page and depending on the hidden input value, different sections are called.
Now my issue is, I have 2 input buttons in one of my forms, and depending on what button I click i need to send the appropriate hidden input type,
For example in the below form .
If i click on Generate password button,
I want the target value(the value of the hidden input field) as generate_password
If I click on Lock Password I want the target value to be user_locked. Here is my code.
puts "<input type=\"hidden\" name=\"target\" value=\"user_locked\">"
puts "<tr><td colspan='4'> New User request Review</td></tr>"
puts "<tr><td><label for=\"full_name\"> Full Name </label></td>"
puts "<td><input type=\"text\" value =\"$name\" name =\"full_name\" readonly=\"readonly\"></td>"
puts "<tr><td><input type=\"button\" value=\"Generate Password\" onclick=\"if(confirm('Are you user you want to add this user?')){submit()};\"></td>"
puts "<td><input type=\"button\" value=\"Lock User\" onclick=\"if(confirm('Are you user you want to add this user?')){submit()};\"></tr>"
well basically I am calling different functions depending upon the hidden field,
set target ""; catch { set target $CGI_DATA(target) }
switch $target {
"confirm" { set id [UpdateUserData $id] }
"user_locked { DeleteUser $id }
"user_confirmed" { NewUserConfirmed}
"newuser" { NewUserReview }
default { }
}
The code to your onclick event could do that when confirming instead of just submitting the form. If you use jQuery:
if(confirm('Are you user you want to add this user?')){
$("input[name=target]").val('Generate password');
submit();
}
The one for the other input button should be very similar.
It is also possible that you have a way of knowing which button was pressed to submit the form another way. If I remember correctly, in PHP at least the name of the button is passed through in the _REQUEST variable.
In HTML:
<input type="hidden" id="target" name="target" value="user_locked">
...
<input type="button" value="Generate Password" id="generate_button"/>
<input type="button" value="Lock User" id="lock_user"/>
In JS (jQuery):
$("#generate_password,#lock_user").click(function(){
("#target").val($(this).attr("id"));
$("form.myform").submit();
});
You can change around the IDs and classes of these elements, but make sure the JS and HTML match up.

JavaScript, HTML, JSP onClick statement

Is there a way to use the value from a text field as the parameter value in an onclick statement for a button. For example if you have some text field named "name" and you have another button named "button" when clicked will go to the same page "page.jsp" with a parameter "par" equal to the text field value. This is what I am currently doing:
out.print("<input type = 'button' name = 'noName' value = 'Click Me' onclick =" + '"' + "window.location.href = 'http://page.jsp?par=" + document.form.name.value + "'" + '"');
But for some reason it doesn't like the par=" + document.form.name.value
Any suggestions?
Like this?
<script>
function doSomething(txt){
alert(txt); //alert the text maybe?
//do more things...
}
</script>
<input onClick="doSomething(this.value)">
this.value means the value in the textfield.
String s = "<input type='button' name='noName' value='Click Me' onclick="
+ "\"window.location.href='http://page.jsp?par="
+ document.form.name.value + "'\"";
Well, that's pretty confusing.
document etc. has zero meaning on the server side. Why aren't you doing this in JavaScript, where it would be a lot easier? Why isn't this in the JSP, where it would be trivial?
If you want to access a form value from a servlet, (a) that form value must have been submitted, and (b) you access it via request.getParameter("parameterName"). But I find it impossible to believe that's the easiest way to do it.

Categories