cant get radio button onchange to work in cakephp - javascript

I dont get any output for my onchange event for a radio button.
I want to select 3 out of 4 a radio buttons and disable a text input field and the other enables the text input.
Currently I cant get it to output anything.
echo $this->Form->input('startDate',array('id'=>'startdatebox','label' => 'Start Date','class'=>'datepicker', 'type'=>'text','style'=>'width:100px;height:30px','value' => $datestart));
..
echo $this -> Form -> input('dateRange',
array('id'=>'dateRange2','label' => '<h6>Date Range</h6>','type' => 'radio',
'value' =>$dateSelect,'name'=>'dateRange2' ,'options' => $selectoption))
;
<script type="text/javascript">
$("input[name='data[User][dateRange2]']").on("click",function() {
$('#startdatebox, #enddatebox').prop('disabled', $(this).val() != 3);
alert( 'aasda');
});

First call onclick on your radio button, as like
echo $this -> Form -> input('dateRange',
array('id'=>'dateRange2',
'label' => '<h6>Date Range</h6>',
'type' => 'radio',
'value' =>$dateSelect,
'name'=>'dateRange2' ,
'options' => $selectoption,
'onclick'=> 'myFunc(this.value)'
)
);
Then Add javascript
<script type="text/javascript">
function myFunc(val) {
if(val != 3) {
document.getElementById("startdatebox").disabled = true;
document.getElementById("enddatebox").disabled = true;
} else {
document.getElementById("startdatebox").disabled = false;
document.getElementById("enddatebox").disabled = false;
}
}
</script>
Or, to change the disabled property of input fields using jQuery 1.6 +
function myFunc(val) {
$('#startdatebox, #enddatebox').prop('disabled', $(this).val() != 3);
}
I hope you may help it.

onChange() is not working for radio button, but it works for checkbox or select.
In order to detect the select action for radios, you have to use onclick() function instead. As Supravat's answer, you need to pass "this.value" in the onclick() function, and you get the selected value in javascript.

Related

jQuery - Check if values of inputs, textareas and select not blank in same function

I have the following code which checks if the values of inputs, textareas and selects are blank, but rather than making functions for each I've tried to store them all into one variable using an array.
But, when the click handler is activated, something is causing the error message to appear even when all inputs on the page are filled in.
Anyone know what might be causing this?
HTML:
$('#saveInvoice').click(function(e) {
e.preventDefault();
var $fields = [ $('input'), $('textarea'), $('select') ];
var $emptyFields = $fields.filter(function() {
return $.trim(this.value) === "";
});
if (!$emptyFields.length) {
saveInvoice();
} else {
alert('Unable to save invoice. There are incomplete item fields.');
}
});
Replace this.value with this.val()
Try the following ...
$('#saveInvoice').click(function(e) {
e.preventDefault();
var $fields = [ $('input'), $('textarea'), $('select') ];
var $emptyFields = $fields.filter(function(element) {
return $.trim(element.val()) === "";
});
if (!$emptyFields.length) {
saveInvoice();
} else {
alert('Unable to save invoice. There are incomplete item fields.');
}
});
you should be getting the value of array elements
You have two problems.
first : Jquery selectors. You've taken array of elements. $('input') gives you nodelist of all the inputs. you need to specify index of input you want to access value. for example $("input")[0] gives you first input found on your page.
second : You need to pass item to filter callback function. inside callback of filter this refer to window.
$('#saveInvoice').click(function(e) {
e.preventDefault();
var $fields = [ $('input')[0], $('textarea')[0], $('select')[0] ];
var $emptyFields = $fields.filter(function(ele) {
console.log(ele.value);
return $.trim(ele.value) === "";
});
if (!$emptyFields.length) {
//saveInvoice();
} else {
alert('Unable to save invoice. There are incomplete item fields.');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
Input : <input type=""><br>
TextArea: <textarea></textarea><br>
Select: <select><option value="1">A</option></select>
<button id="saveInvoice">Save</button>
</form>

Validate checkbox using JavaScript.

I would like some help with checkbox validation.
If you look in below picture, when user click the image, the checkbox becomes selected.
What I would want is if all checkbox are selected alert an simple message.
This is a code to select checkbox by clicking on an image.
$( document ).ready(function() {
$("#roll-<?php echo $row['id_vnr']; ?><?php echo $cut_counter; ?>").click (function(){
var $$ = $(this)
if( !$$.is('.checked')){
$$.addClass('checked');
$('#imgCheck-<?php echo $row['id_vnr']; ?><?php echo $cut_counter; ?>').prop('checked', true);
}
});
});
So I can select check box by clicking on an image. How I can alert message if all check box are selected. Soon user click last picture, the picture will disappear, the red tick box will appear and user should see alert message.
Thank you in advance.
You can achieve this by getting the number of elements with the class 'checked'. If the number is 6, then you can show the alert.
Try this way:
var checkboxes = $('[type="checkbox"]');
checkboxes.on('change', function() {
var checked = $('[type="checkbox"]:checked');
console.log('all:', checkboxes.length, ' / ', 'checked:', checked.length);
if (checkboxes.length === checked.length) {
console.log('ALL CHECKED!');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox">1
<input type="checkbox">2
<input type="checkbox">3
You can use the following javascript code:
$(function(){
$('input[type="checkbox"]').click(function() {
totalCheckboxCount = $('input[type="checkbox"]').length;
selectedBoxesCount = $('input[type="checkbox"]:checked').length;
if(totalCheckboxCount == selectedBoxesCount) {
alert("All checkboxes selected!");
}
});
});

localStorage : store checkboxes automatically checked

I have something like this in php:
if(isset($_POST['submit']){
$check = in_array($row['service_object_id'], $values) ? 'checked' : '';
}
echo '<input type="checkbox" class="faChkRnd" id="'.$row['service_object_id'].'" name="list[]" value="'.$row['service_object_id'].'" '.$check.'>';
Each time I press a submit button, it will check the checkboxes with values inside $check.
It's working good but I want to store the checkboxes checked in localStorage automatically after pressing the button.
I already use this script to store them after click, but it won't work automatically :
<script type = "text/javascript">
$('.faChkRnd').on('click', function() {
var fav, favs = [];
$('.faChkRnd').each(function() { // run through each of the checkboxes
fav = {id: $(this).attr('id'), value: $(this).prop('checked')};
favs.push(fav);
});
localStorage.setItem("favorites", JSON.stringify(favs));
});
$(document).ready(function() {
var favorites = JSON.parse(localStorage.getItem('favorites'));
if (!favorites.length) {return};
console.debug(favorites);
for (var i=0; i<favorites.length; i++) {
console.debug(favorites[i].value == 'on');
$('#' + favorites[i].id ).prop('checked', favorites[i].value);
}
});
</script>
Any ideas ? Thank you !
you shound check type of favorites[i].value. string or boolean !?
string :
if(favorites[i].value == "true") {
$('#' + favorites[i].id ).prop('checked',true);
}
boolean :
$('#' + favorites[i].id ).prop('checked',favorites[i].value);
example :
string : https://jsfiddle.net/utm4za2p/1/
boolean : https://jsfiddle.net/utm4za2p/3/
You can use submit method.
You have a form with the submit button and you have to change it to just a regular button.
And you should put
$('.yourForm').submit()
to the end of click handler where you save the values to the localStorage.
Because when you press the submit button it may triggered before your click handler.
You need save values first and then submit form.

Validating a form to not submit on empty input boxes

// html
<label>Write Data:</label>
</br>
<input type=text id=data name="data"style="width: 14em;">
</br>
</br>
<button id="write" type="submit" formaction="/output4" formmethod="post" style="width: 5em;">Write</button>
<button id="More" type="submit">Add more Parameters</button>
// js
$('#write').click(function(){
$('#data').each(function() {
if ($(this).val() == "" || $(this).val() == null) {
alert("Write Data must be filled out or Remove empty parameter list!");
return false;
}
});
});
I have a program where if a user clicks on a button, more write data boxes are appended. I do not want the form to submit unless all the write data boxes are filled out. The snippet above shows the alert box if an input if incomplete but then when you press ok, the form still submits?
You can use the .submit() event handler. Then use either return false or e.preventDefault() to stop the submit. Also note that id's are unique so $('#data') will only be a single element, so the .each() isn't needed:
$('#formIDHere').submit(function(e){
if ($('#data').val() == "" || $('#data').val() == null) {
alert("Write Data must be filled out or Remove empty parameter list!");
e.preventDefault(); // or `return false`
}
});
For many inputs have your input items be a class with the value class="data". Just note you need to to use e.preventDefault() using the e from the submit event. In this case return false is for the .each() and not the submit. I use it here to stop the .each from going so we don't have many unneeded alerts and checks:
$('#myForm').submit(function(e){
$('.data').each(function(){
if ($(this).val() == "" || $(this).val() == null) {
alert("Write Data must be filled out or Remove empty parameter list!");
e.preventDefault(); // This is the preventDefault of submit
return false; // This stops the .each from continuing
}
});
});
Demo
$('#write').click(() => {
// if any one of the inputs is blank canSubmit will end up as false
// if all are not blank, it will end up as true
var canSubmit = [...document.querySelectorAll('input')]
.reduce((acc, input) => acc = input.value === '' ? false : acc , true)
});
<script type="text/javascript">
$(function () {
$("#data").bind("change keyup", function () {
if ($("#data").val() != "")
$(this).closest("form").find(":submit").removeAttr("disabled");
else
$(this).closest("form").find(":submit").attr("disabled", "disabled");
})
});
</script>
This would allow you to disable your submit button until there was data within the input field.

How to check all boxes when using function form_checkbox() php

Hi guys i have two checkboxes.
<li>
<?=form_checkbox('heart_rate', 'yes', sel_checkbox($admission['heart_rate'], $observation[0]->heart_rate))?>
<?=form_label('Heart Rate')?>
</li>
<li>
<?=form_checkbox('blood_pressure', 'yes', sel_checkbox($admission['blood_pressure'], $observation[0]->blood_pressure))?>
<?=form_label('Blood Pressure')?>
</li>
i want to create a third checkbox labelled all so that when it is ticked all my checkboxes are ticked. Any ideas?
Useing jQuery this can be done very easily, just give id to the check all checkbox checkAllId:
And the following code will check all the checkbox:
$('#checkAllId').change(function(){
if($(this).attr('checked')){
//uncheck all the checkboxes
$("input[type='checkbox']").each(
function() {
$(this).attr('checked',false);
}
);
}else{
//check all the checkboxes
$("input[type='checkbox']").each(
function() {
$(this).attr('checked',true);
}
);
}
});
you will have to give id to checkbox as:
I think you have not given id properly try this :
<?php
$data = array(
'name'=> 'checkAllId',
'id'=> 'checkAllId',
);
form_checkbox($data)
?>
Also confirm in the firebug whether id is coming properly or not.
Hope this will help!
$(function(){
$('input[class=3rd]').on('click',function(){
var this = $(this);
if($(this.':checkbox:checked').length > 0)
{
// If 3rd is checked, check all
$('.1st').prop('checked', true);
$('.2nd').prop('checked', true);
}
else
{
// Esle uncheck all
$('.1st').prop('checked', false);
$('.2nd').prop('checked', false);
}
})
})

Categories

Resources