Append result by group - javascript

I have a simple function that I'm trying to append the results by group. I've been able to display the result for a single form but unsure where to proceed. Here is the function on Jsfiddle. http://jsfiddle.net/XBSVn/

try this. note that there is difference between your class names, and your selector only selects first input element:
$(function() {
$('.ratingroups input').each(function(i, v) {
var star = '&#9733';
var val = parseInt(this.value, 10)
for (var i = 0; i < val; i++) {
$(this).parent().siblings('div').append($('<div>').html(star).text())
}
});
});
DEMO

The issue here is with the typos in the class names selectors(you used .ratinggroups and .ratingroups) and also the textbox selector(you were always getting the first text box to check the value).
Check this updated JsFiddle: http://jsfiddle.net/XBSVn/12/
Change your HTML to:
<form class="ratingroups">
<p><input class="asstars" value="5"/> </p>
<div class="rstars"></div>
</form>
<form class="ratingroups">
<p><input class="asstars" value="4"/> </p>
<div class="rstars"></div>
</form>
<form class="ratingroups">
<p><input class="asstars" value="3"/> </p>
<div class="rstars"></div>
</form>
<form class="ratingroups">
<p><input class="asstars" value="2"/> </p>
<div class="rstars"></div>
</form>
<form class="ratingroups">
<p><input class="asstars" value="1"/> </p>
<div class="rstars"></div>
</form>
and your Javascript to:
$(function() {
console.log($('.ratingroups input').length);
$('.ratingroups input').each(function() {
var asstars = $(this);
var stars = asstars.closest('.ratingroups').find('.rstars');
var display = true;
if (asstars.val() == '5') {
stars.append('<span>★★★★★</span>');
display = false;
}
else if (asstars.val() == '4') {
stars.append('<span>★★★★</span>');
display = false;
}
else if (asstars.val() == '3') {
stars.append('<span>★★★</span>');
display = false;
}
else if (asstars.val() == '2') {
stars.append('<span>★★</span>');
display = false;
}
else if (asstars.val() == '1') {
stars.append('<span>★</span>');
display = false;
}
if (display) {
stars.css('display', 'none');
}
else {
stars.css('display', 'block');
}
});
});

Related

Check if input value was empty change text

I wrote the below code for changing the text of div that called active yes, based on value of each input with type hidden.
i want to change the text of this div if input with id enable to "Enable List" and if input with classname delete has value changes the div text to "Deleted list" and if both of them was null show "list".
my code does not work correctly.
what is my problem?
here is my snippet :
$(document).ready(function() {
tmpval = $('#enable').val();
if (tmpval == '') {
$('.activeyes').text('list');
} else {
$('.activeyes').text('Enable List');
}
tmpval2 = $('#delete').val();
if (tmpval2 == '') {
$('.activeyes').text('List');
} else {
$('.activeyes').text('Deleted List');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<input type="text" value="aa" id="enable" />
<input type="text" value="" id="delete" />
<h1 class="activeyes"> List</h1>
You are overwriting effect of the first check by the second check; you need to check the 2 inputs value together. Still, it is unclear what will happen if both are non-empty.
$(document).ready(function() {
tmpval = $('#enable').val();
tmpval2 = $('#delete').val();
if (tmpval == '' && tmpval2 == '') {
$('.activeyes').text('list');
} else if( tmpval!='' ){
$('.activeyes').text('Enable List');
} else if( tmpval2!='' ){
$('.activeyes').text('Deleted List');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<input type="text" value="aa" id="enable" />
<input type="text" value="" id="delete" />
<h1 class="activeyes"> List</h1>
what is my problem?
You need to check the value of input when it changes its value, so capture the change event.
$(document).ready(function() {
$('#enable, #delete').change(function() {
var $this = $(this);
var id = $this.attr("id");
var value = $this.val();
if (value.length == 0)
{
$('.activeyes').text('list');
}
else
{
id == "enable" ? $('.activeyes').text('Enable List') : $('.activeyes').text('Deleted List');
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<input type="text" value="aa" id="enable" />
<input type="text" value="" id="delete" />
<h1 class="activeyes"> List</h1>

JavaScript Form Validation Function: Looping each item

I have a list of form input elements on which I want to run a loop. From the result, I need to run a few conditional statements so that I can validate them using their name attributes. I've used jQuery for that and used .each method for looping through them. Thus I can add/remove class name to invalid input elements.
It's little difficult to describe in words. But the code block bellow will make sense:
JSFiddle
function formValid() {
var valid = true;
$('form input').each(function() {
if ($(this).val() == '') {
valid = false;
$(this).addClass('red-border');
} else if (true /* if "tel" is not a number */ ) { // <- here I want to validate using input name attribute
valid = false;
$(this).addClass('red-border');
} else {
$(this).removeClass('red-border');
}
});
return valid;
}
$('form').on('submit', function(event) {
event.preventDefault();
if (formValid()) {
alert('Yay!');
}
});
.red-border {
border-color: red !important;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="#">
<p>
<input type="text" name="name">
</p>
<p>
<input type="text" name="tel">
</p>
<p>
<input type="text" name="email">
</p>
<p>
<button type="submit">Submit</button>
</p>
</form>
Check out the fiddle
https://jsfiddle.net/t9ayvken/
CSS:
.red-border {
border-color: red;
}
HTML:
<form action="#">
<p>
<input class="must-validate" type="text" name="name">
</p>
<p>
<input class="must-validate" type="text" name="tel">
</p>
<p>
<input class="must-validate" type="text" name="email">
</p>
<p>
<button type="submit">Submit</button>
</p>
</form>
JQuery:
/*validation functions for each input type*/
function validateName(event){
var $this = $(this);
/* validation is done here */
if(false){
$this.removeClass('red-border');
}
else {
/* not valid*/
$this.addClass('red-border');
}
}
function validateTel(event){
}
function validateEmail(event){
}
/*add validation event handlers*/
$(document).on('validate','[name="name"]',validateName);
$(document).on('validate','[name="tel"]',validateTel);
$(document).on('validate','[name="email"]',validateEmail);
function formValid() {
var valid = true;
/*Trigger validation events for all required inputs*/
$('input.must-validate').trigger('validate');
/* After validation is complete check to see if any are invalid */
if( $('input.must-validate.red-border').length ){
alert('the form is invalid');
valid = false;
}
return false;
//return valid;
}
$('form').on('submit', function(event) {
event.preventDefault();
if ( formValid() ) {
alert('Yay!');
}
});
I suggest returning a list of errors instead of a boolean flag.
function formValid() {
var errorMsgs = [];
$('form input').each(function() {
var msg = [],
val = $(this).val();
// Check blanks
if (val == '')
msg.push( `${$(this).attr('name')} is blank`);
// Check numbers
if ($(this).attr('name') === 'tel' && isNaN(val))
msg.push( `${$(this).attr('name')} is not a number`);
// Handle results
if (msg.length > 0){
errorMsgs.push(...msg);
$(this).addClass('red-border');
} else {
$(this).removeClass('red-border');
}
});
return errorMsgs;
}
$('button').on('click', function(event) {
var errors = formValid();
if (errors.length === 0) {
alert('Yay!');
} else {
alert(errors.join('\r'));
}
});
.red-border {
border-color: red !important;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="#">
<p>
<input type="text" name="name">
</p>
<p>
<input type="text" name="tel">
</p>
<p>
<input type="text" name="email">
</p>
<p>
<button type="submit">Submit</button>
</p>
</form>

Validate Numbers Javascript

I have written the code so far and came up with this. I have to
Make sure the user input numbers into the text boxes and I was given errors using the Xhtml format, one, the '&&' sign gave me errors and due to online help, I was told I needed to use //
As I student learning Javascript I have no idea what this is or means, but as I placed it there, I was given more errors and my code crashed up after the javascript was added.
Thanks for the help in advance
<head>
<script type = 'text/javascript'>
// <![CDATA[
$('#submit').click(function(){
validateRange();
validateRa();
})
function validateRange() {
var txtVal = document.getElementById("CustomerID").value;
var txtVal1=parseInt(txtVal);
if (txtVal1 >= 3000 && txtVal1 <= 3999) {
return true;
}
else {
alert('Please enter a number between 3000-3999');
return false;
}
}
function validateRa() {
var txtVal1 = document.getElementById("AcctNo").value;
var txtVal2=parseInt(txtVal1);
if (txtVal2 >= 90000 && txtVal2 <= 99999) {
return true;
}
else {
alert('Please enter a number between 90000-99999');
return false;
}
}
// ]]
</script>
<title>Account Lookup</title>
</head>
<body>
<h1> Please Provide Your Information</h1>
<p><input type="text" id="AcctNo" value="Account Number"/></p>
<p><input type="text" id="CustomerID" value="CustomerID" onchange="validateRange()"/></p>
<p><input type="text" name="Type" value="Account Type" onchange="validateRange()"/></p>
<p><input type="text" name="balance" value="Balance"/></p>
<p class="submit" />
<input type="submit" name="commit" value="Submit" id="submit" /><button type="reset" value="Clear">Clear</button></p>
</body>
</html>
EDITED
try using this:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('#submit').click(function(){
validateRange();
validateRa();
});
});
function validateRange() {
var txtVal = document.getElementById("CustomerID").value;
var txtVal1=parseInt(txtVal);
if (txtVal1 >= 3000 && txtVal1 <= 3999) {
return true;
}
else {
alert('Please enter a number between 3000-3999');
return false;
}
}
function validateRa() {
var txtVal1 = document.getElementById("AcctNo").value;
var txtVal2=parseInt(txtVal1);
if (txtVal2 >= 90000 && txtVal2 <= 99999) {
return true;
}
else {
alert('Please enter a number between 90000-99999');
return false;
}
}
</script>
<html>
<title>Account Lookup</title>
<body>
<h1> Please Provide Your Information</h1>
<p><input type="text" id="AcctNo" value="Account Number"/></p>
<p><input type="text" id="CustomerID" value="CustomerID" onchange="validateRange()"/></p>
<p><input type="text" name="Type" value="Account Type" onchange="validateRange()"/></p>
<p><input type="text" name="balance" value="Balance" /></p>
<p class="submit" />
<input type="submit" name="commit" value="Submit" id="submit" /><button type="reset" value="Clear">Clear</button></p>
</body>
</html>
BTW the function validateRa missing the closing curly braces you need to add } before // ]]
function validateRa() {
var txtVal1 = document.getElementById("AcctNo").value;
var txtVal2=parseInt(txtVal1);
if (txtVal2 >= 90000 && txtVal2 <= 99999) {
return true;
}
else {
alert('Please enter a number between 90000-99999');
return false;
}
} //<= this is missing in your code
// ]]

Pass jQuery array value on submit as hidden input

On button press the following code will display a message with values collected from all checkboxes. But I want to pass these values (returned by function) as hidden input on submit.
<form action="script.php" method="post">
<input type="checkbox" name="chb1" value="html" />HTML<br/>
<input type="checkbox" name="chb2" value="css" />CSS<br/>
<input type="checkbox" name="chb3" value="javascript" />JavaScript<br/>
<input type="checkbox" name="chb4" value="php" />php<br/>
<input type="checkbox" name="chb5" value="python" />Python<br/>
<input type="checkbox" name="chb6" value="net" />Net<br/>
<input type="button" value="Click" id="btntest" />
</form>
<script type="text/javascript"><!--
function getSelectedChbox(frm) {
var selchbox = [];
var inpfields = frm.getElementsByTagName('input');
var nr_inpfields = inpfields.length;
for(var i=0; i<nr_inpfields; i++) {
if(inpfields[i].type == 'checkbox' && inpfields[i].checked == true) selchbox.push(inpfields[i].value);
}
return selchbox;
}
document.getElementById('btntest').onclick = function(){
var selchb = getSelectedChbox(this.form);
alert(selchb);
}
//-->
</script>
I've seen guys like you trying to code my router interface, so I'll help out.
give your form an id cause you'll need it later
<form action="script.php" method="post" id="the_form">
add the hidden input in the form
<input type="hidden" name="values" id="values" value="" />
the button in the form matures to a real submit (amazing)
<input type="submit" ...
your "getSelectedChbox()" function is amazing; don't change anything there, just wanted to give you congratulations for it, it's a great function
now, where it says document.getElementById('btntest').onclick - get rid of all that and add this code instead; this code will do the rest.
document.getElementById('the_form').onsubmit = function(){
var selchb = getSelectedChbox(this);
var values = selchb.join(', ');
if(!values.length){
alert('There was an error. You have to select some checkboxes. ');
return false;
}
document.getElementById('values').value = values;
if(!confirm(" Are you interested in submitting this form now? If not, click accordingly. "))
return false;
}
Or simply copy-paste this whole thing in a file called script.php:
<?php echo var_dump(isset($_POST['values']) ? $_POST['values'] : 'Submit first.'); ?>
<form action="script.php" method="post" id="the_form">
<input type="checkbox" name="chb1" value="html" />HTML<br/>
<input type="checkbox" name="chb2" value="css" />CSS<br/>
<input type="checkbox" name="chb3" value="javascript" />JavaScript<br/>
<input type="checkbox" name="chb4" value="php" />php<br/>
<input type="checkbox" name="chb5" value="python" />Python<br/>
<input type="checkbox" name="chb6" value="net" />Net<br/>
<input type="hidden" name="values" id="values" value="" />
<input type="submit" value="Click" id="btntest" />
</form>
<script type="text/javascript"><!--
function getSelectedChbox(frm) {
var selchbox = [];
var inpfields = frm.getElementsByTagName('input');
var nr_inpfields = inpfields.length;
for(var i=0; i<nr_inpfields; i++) {
if(inpfields[i].type == 'checkbox' && inpfields[i].checked == true)
selchbox.push(inpfields[i].value);
}
return selchbox;
}
document.getElementById('the_form').onsubmit = function(){
var selchb = getSelectedChbox(this);
var values = selchb.join(', ');
if(!values.length){
alert('There was an error. You have to select some checkboxes. ');
return false;
}
document.getElementById('values').value = values;
if(!confirm(" Are you interested in submitting this form now? If not, click accordingly. "))
return false;
}
//-->
</script>
Have fun.

Validation for radio button using javascript

I have 2 radio buttons. I need to give validations for radio button using javascript. Please tel me whats wrong with my code. Here is the code.
$(function() {
$("#XISubmit").click(function(){
var XIGender= document.forms["XIForm"]["XIGender"].value;
if (XIGender==null || XIGender=="") {
alert("Please select the gender");
return false;
}
document.getElementById("XIForm").submit();
});
Here is my HTML code:
<label>Gender </label> &nbsp&nbsp
<input type='radio' name='XIGender' value='Male' id="XImale"/>Male
<input type='radio' name='XIGender' value='Female' id="XIfemale"/>Female</td>
One more here,
$(document).ready(function() {
$("#XISubmit").click(function () {
if($('input[name=XIGender]:checked').length<=0){
alert("Please select the gender");
return false;
}
$( "#XIForm" ).submit();
});
});
JSFiddle
Here is the code. You will have to create a form and validate it on submit.
HTML:-
<form name="myForm" action="targetpage.asp" onsubmit="return validateForm();" method="post">
<label>Gender</label>&nbsp&nbsp
<input type='radio' name='XIGender' value='Male' id="XImale" />Male
<input type='radio' name='XIGender' value='Female' id="XIfemale" />Female</td>
<input type="submit" value="submit" id="XISubmit" />
</form>
JS:-
function validateForm() {
if (validateRadio(document.forms["myForm"]["XIGender"])) {
alert('All good!');
return false;
}
else {
alert('Please select a value.');
return false;
}
}
function validateRadio(radios) {
for (i = 0; i < radios.length; ++i) {
if (radios[i].checked) return true;
}
return false;
}
Hope this will help you. :)
Enjoy coding.
<form name="formreg" enctype="multipart/form-data" method="post">
<input type="radio" value="male" name="gender" /> Male<br />
<input type="radio" value="female" name="gender" /> Female<br />
<input value="Submit" onclick="return inputval()" type="submit" />
</form>
JS:
<script type="text/javascript">
function inputval() {
var $XIForm = $('form[name=XIForm]');
if ($("form[name='formreg'] input[type='radio']:checked").length != 1) {
alert("Select at least male or female.");
return false;
}
else {
var gender = $("input").val();
//alert(gender);
$XIForm.submit();
alert(gender);
}
}
</script>
You can't get the value of the radio button like that. document.forms["XIForm"]["XIGender"] will return more than one node and you can't get the value property of a list of nodes. Since your using jQuery, this can be made much easier:
$("#XISubmit").click(function () {
var $XIForm = $('form[name=XIForm]');
var XIGender = $XIForm.find('input[name=XIGender]:checked').val();
if (XIGender == null || XIGender == "") {
alert("Please select the gender");
return false;
}
$XIForm.submit();
});
JSFiddle
Use the :checked selector as below
function() {
var len = $("input:checked").length;
if(len == 0) {
alert("Please select a gender");
return false;
}
see fiddle

Categories

Resources