I have a problem, i have X <input type="checkbox" /> in my code, now I want to foreach this object/array its out put. - look my code.
$("#denied_seekrs").click(function()
{
if (!isCheckedById("selectname"))
{
alert ("Please select at least one event");
return false;
}
else
{
alert( $("input[#id=selectname]:checked").val() ); //submit the form
}
});
function isCheckedById(id)
{
var checked = $("input[#id="+id+"]:checked").length;
if (checked == 0)
{
return false;
}
else
{
return true;
}
}
When I output it in alert i get a object, but if I have select 2 checkbox I what the value in this 2 checkboxes.
I hope I can be helpful and all here understand me :)
How about
$("#denied_seekrs").click(function() {
var checkedInputs = $("input:checked");
var test = "";
$.each(checkedInputs, function(i, val) {
test += val.value+",";
});
test = test.substring(0,(test.length-1));
alert(test);
});
I'm not exactly sure what you're looking for, but I'm guessing that the jQuery.each() method will help. You can use it to iterate over arrays, objects, and more.
var arr = [ "one", "two", "three", "four", "five" ];
jQuery.each(arr, function() {
$("#" + this).text("My id is " + this + ".");
return (this != "four"); // will stop running to skip "five"
});
how about something like this:
jQuery.each(checked, function() {
$(checked + this).text("My id is " + this + ".");
});
Can it be that - ultimately - you are looking for $.serializeArray() or $.serialize()?
If not, then maybe this is helps you:
$("#denied_seekrs").click(function()
{
if (!isCheckedById("selectname"))
{
alert ("Please select at least one event");
return false;
}
else
{
// prepare array of values
var values = [];
// prepare list of checked checkboxes
var $checkboxes = $("input[#id=selectname]:checked");
// push each individual value into the array
$checkboxes.each(function() { values.push( $(this).val() ); });
// debug output
alert( values.join("\n") );
//submit the form
}
});
When I got you right, you want the user to select one checkbox (or is it one or more?). This should do it:
$("#denied_seekrs").click(function()
{
var $checkedInputs = $("input:checked");
if ($checkedInputs.length != 1)
{
alert ("Please select one event");
return false;
}
alert( $checkedInputs.val() ); //submit the form
});
EDIT:
After reading your question again, I realized that the above code does not answer your question. However, the above does work and is a much shorter version of your solution. Maybe you want to use it instead. To answer your question, you could alert the value of all checked boxes like this:
Change this:
alert( $checkedInputs.val() ); //submit the form
to this:
var values = "";
$checkedInputs.each(function(){
values += $(this).val() + " ";
});
alert( values );
Related
I am working on form input field and trying to show error message when user enters any of the following text
JS01, PR03, HY79, FG36, VF42, HF23
Basically need to show error message only if user entered the above mentioned text.
<input type="text" name="prodcode" class="form-control"/>
Should we use regex to achieve this? or Any jquery/javascipt can do this?
Can anyone provide me an example?
use Jquery.inArray method to find out if the word user entered is in your defined array,
var myarray = ["JS01", "PR03","HY79","FG36", "VF42","HF23"];
var inputWord = $("input[name='prodcode']").val();
if(jQuery.inArray(inputWord , myarray) !== -1){ //if the word exits
//do what you want here
}
You can use jquery indexof method.For ex:-
a = [JS01, PR03, HY79, FG36, VF42, HF23]
var value = $('input[name="prodcode"]').val();
var indexval = a.indexOf("value" ); // this will return -1 if not found else return index
if (indexval>=0){
// code for error
}
Please Check this. The solution has been done on keydown
$(function(){
var arr = ['JS01', 'PR03', 'HY79', 'FG36', 'VF42', 'HF23'];
$('.form-control').keydown(function(){
var inputval = $('.form-control').val();
var k = $.inArray(inputval,arr);
if(k != -1){
alert('error');
}
});
});
Try with this:
var err = [ 'JS01', 'PR03', 'HY79', 'FG36', 'VF42', 'HF23' ];
$('#myInput').keyup(function (e){
console.log("ERR", err.indexOf(this.value))
if (err.indexOf(this.value) !== -1) {
$('.error').css({display: 'block'})
} else {
$('.error').css({display: 'none'})
}
})
.error{
color: red;
display:none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="myInput" type="text" name="prodcode" class="form-control"/>
<div class="error">Error</div>
You can use the includes method ( MDN includes ) and check against an array which is prefilled with invalid strings.
var valuesToCheckFor = ["JS01", "PR03","HY79","FG36", "VF42","HF23"];
if( valuesToCheckFor.includes($('input[name="prodcode"]').val()) ) {
// Do what you want.
}
P.S. you will have to add this code inside the submit handler.
So I have a 2 multiple select box (one for the floor and one for the room). The values in the Room depends on the Floor. If you choose Floor: 001 all the values in the Room will start on 1 and if you choose Floor: 002 all the values in the Room will start in 2, and so on. But when I select the values in the Room all of the values will disappear, here's my script:
<script type="text/javascript">
$(document).ready(
function()
{
var selectArr = [];
$("select").change(function(){
var arr = $(this).val()
selectArr.push(arr);
console.log(arr)
populateRooms();
clearArray();
});
function clearArray() {
return selectArr = []
}
function populateRooms() {
$.ajax({
type: "GET",
url: "/hms/shifts/" + selectArr,
success: function (response) {
$('#_rooms_id').empty();
var myObject = eval('(' + response + ')');
for (i in myObject)
{
$('#_rooms_id').append(
$('<option></option>',
{
value: myObject[i]["id"],
text: myObject[i]["roomNumber"]
}
)
);
}
},
error: function (e){
alert("Error" + e)
}
});
}
});
</script>
I think it's because of the .empty() but if I remove that all of the values in room will show, there will be no filter. I hope someone can help me. Newbie here. Thank you.
I guess you should add the event to populate rooms-select only in the floor-select
This code add the onChange event to ALL dropdowns in your code:
$("select").change(function(){
var arr = $(this).val()
selectArr.push(arr);
console.log(arr)
populateRooms();
clearArray();
});
Change to this:
$("#floors-dropdownId").change(function(){
var arr = $(this).val()
selectArr.push(arr);
console.log(arr)
populateRooms();
clearArray();
});
You have applied generic 'change' event on all select which causes it to clear.
//you have issue here , $(select) means all selects in your current DOM!
$("select").change(function(){
var arr = $(this).val()
selectArr.push(arr);
console.log(arr)
populateRooms();
clearArray();
});
Chang to ,
// Apply change on specific instead
$("select#floorId").change(function(){
var arr = $(this).val()
selectArr.push(arr);
console.log(arr)
populateRooms();
clearArray();
});
I have html running javascript after form,
form name="mortgage" method="post" action=" "onsubmit="return completeFormValidation();">
And javascript code for validation,
function completeFormValidation() {
location();
} // End of completeFormValidation
function location(){
var numradio = document.mortgage.propLocation.length;
var selected="";
for(var i=0; i < numradio; i++){
if(document.mortgage.propLocation[i].checked == true){
selected += "Selected radio item " + i;
}
}
if(selected == ""){
document.getElementById("reserved").innerHTML = "<p> none radio selected </P>";
return false;
}
}
The code works perfectly fine in dream weaver but in browsers doesn't seem to work instead it will submit even if radio buttons aren't selected. Please help me out thanks.
because you are not returning the "FALSE/TRUE" value from completeFormValidation function.. And Change the name of the function Location is reserved by JavaScript.
check the jsfiddle
function completeFormValidation() {
return my_location();
}
its always better to return the value from location true OR false
you can modify your my_location() as below
function my_location(){
var numradio = document.mortgage.propLocation.length;
var selected="";
for(var i=0; i < numradio; i++){
if(document.mortgage.propLocation[i].checked == true){
selected += "Selected radio item " + i;
}
}
if(selected == ""){
document.getElementById("reserved").innerHTML = "<p> none radio selected </P>";
return false;
}
else{
return true;
}
}
try to replace
function completeFormValidation() {
location();
} // End of completeFormValidation
by
function completeFormValidation() {
return location();
} // End of completeFormValidation
Rename your location function. location is a native property of the window object and can not be redefined.
I have the following in my HTML thing, The input value will be populated by the user selection and store the values in the format of array( 45[45, 6, 33], 67[67,2,5] and so on.. ). Basically the value would be like the following:
<input id="question_string" type="hidden" value="{}">
<input class="submit_updates" name="commit" type="submit" value="Process">
Now i need to disable the submit button or alert some messages like 'Select all values' if the input has no arrays in the {}.
Updated:
var question_hash_element = document.getElementById('question_string');
var question_hash = JSON.parse(question_hash_element.value);
var myArray = new Array();
myArray[0] = window.batch_question_id;
myArray[1] = window.answer_id || window.answer_text || window.batch_answer_checkbox
myArray[2] = window.build_id
This bit of above code store the values into the {}. I just want to disable and let the user to select all the fields to process the form. If the values are {}, the button should disabled. and any of the values inside and it should be enabled.
I have tried like the following:
$('.submit_updates').click(function () {
if ($('#question_string') == {}) {
return false;
alert("Select all the Values");
} else {
return true;
}
});
It's not working..
Any help would be appreciated! Thanks
$('.submit_updates').on('click', function (e) {
e.preventDefault();
if ( $.trim($('#question_string').val())=='{}' ) {
alert('no question !');
}else{
this.form.submit();
}
});
You are returning false before alerting the message.
Try this:
$('.submit_updates').on("click", function () {
if ($('#question_string').val() == "{}") { //Adjusted condition
//Alert message
alert("Select all the Values");
//Disable the submit button
$(".submit_updates").prop("disabled", true);
return false;
} else {
return true; //Not really needed
}
});
It is nicer to use on and prop instead of click and attr, as #adeneo suggests.
Try this
$(function(){
$('.submit_updates').on('click', function () {
if ($('#question_string').val() == "{}") {
$(this).prop('disabled', 'disabled');
alert("Select all the Values");
} else {
}
});
});
DEMO
I am trying to do some simple form validation using javascript object values. I know it's not "ideal", but I'm just working with a simple form that doesn't need to be iron-clad.
Please see my fiddle example: http://jsfiddle.net/6dXd7/3/
I am trying to make sure that each form field has a value. If so, set the value for myObj.fieldID to yes.
Then, when the form is submitted, check every existing myObj.XXX and be sure all their values are yes.
In my example, I am having trouble creating the object, and I don't know how to cycle through all the objects when the submit button is pressed without specifying each one by name.
Here's the code in the jsfiddle example linked to above:
<script>
$(document).ready(function () {
var myObj = {};
$("input.checkblank").blur(function () {
var inputID = $(this).attr("id");
var contents = $("input#" + inputID).val();
if (contents == "") {
$(myObj).data(inputID, "no");
} else {
$(myObj).data(inputID, "yes");
}
});
$("#verify").click(function () {
if (myObj.first && myObj.second == "yes") {
// ***** Trying to get it to scan through ALL existing myObj's and make sure all their values are "yes" *****
$('.results').text('all good');
} else {
$('.results').text('not good');
}
});
});
</script>
<input type="text" name="first" id="first" class="checkblank"><br />
<input type="text" name="second" id="second" class="checkblank">
check<br />
<p class="results"> </p>
You were storing field info in jQuery DATA and trying to check them later not in the same place...
var obj = {}
$(obj).data('a','1');
console.log(obj.a); //this will log null, cause there's no attribute 'a' in 'obj'
console.log($(obj).data('a')); //this will log '1' :]
instead do this, you should store you data in attributes from native object like this:
var obj = {}
obj['a'] = '1'; //obj.a = '1' work's too
console.log(obj.a); //now it log '1' :]
Also, your verification function is wrong.. it only check if first exists inside myObj and if second exists and is equal to "yes". So your verification function should be something like this:
$("#verify").click(function() {
var allFieldsOK = false;
for ( var field in checkedFields ) {
if ( !(allFieldsOK = checkedFields[field] ) ) break;
}
$('.results').text( allFieldsOK ? 'all good' : 'not good' );
});
Here is an update to you jsFiddle, it is working for you purpose and should work if you add more input fields with the class checkblank :]
http://jsfiddle.net/6dXd7/5/
replace this
$("#verify").click(.........});
with this
$("#verify").click(function() {
var flag=true;
$('.checkblank').each(function(){ //check all elements with class checkblank
if($(this).val().length==0) //set flag false if anyone of them is blank
flag=false;
})
if (flag) {
$('.results').text('all good');
} else {
$('.results').text('not good');
}
});
...it should work