I have a drop down which may or may not change the value of a hidden field. The change is decided by a calculation function.
I want to track the change in the hidden field. If there is any change, I want to check a checkbox.
How can this be achieved?
I cannot change my HTML. Hence everything is has be handled in the JS.
<input type="hidden" name="03Text" value="">
In Java script:
var w = dojo.query('[type$=hidden]');
w.forEach(function(node, index, nodelist){
dojo.connect(node , "onchange", function(evt){
controlapiObj.setControlAttribute(payload.srcFormId, payload.outputParams[0], true, "checked");
});
});
I use dojo.query because there are many such hidden fields in the form, and I have to monitor the value change of all.
*emphasized text*I believe the problem is with the the "onchange" event not firing when you programmatically change the value of the hidden field. You can trigger this event manually the same time the value of the field is changed like so. My example uses dojo 1.10 and the on function
HTML:
<input type="hidden" name="03Text" value="1">
<input type="hidden" name="03Text" value="2">
<input type="hidden" name="03Text" value="3">
SCRIPT:
require(["dojo/query", "dojo/on", "dojo/domReady!"], function(query, on){
var w = query('[type$=hidden]');
w.forEach(function(node, index, nodelist){
on(node, "onchange", function(){
console.log(node);
})
});
var event = new Event('onchange');
w[0].dispatchEvent(event);
w[1].dispatchEvent(event);
w[2].dispatchEvent(event);
})
Jsfiddle with example:
http://jsfiddle.net/kagant15/ay1dzqqg/
Related
I've achieved the first part of the question using php or js. I use php to echo checked attribute. The problem here is that the radio inputs have other inputs that become visible upon selection with onchange event. However, if any of the radio gets selected/checked by default, the conditional inputs aren't displayed until I change the radio selections. Hence the question, how do I get it checked by default and still have the respective conditional inputs displayed.
<input name="mode" id="single" onchange="conditionalDisplay(this.value)" type="radio" value="single" <?php if($mode == single){echo 'checked';}>
<input name="mode" id="multi" onchange="conditionalDisplay(this.value)" type="radio" value="multi" <?php if($mode == multi){echo 'checked';}>
When single is selected, other inputs become visible. Same goes for multi. If the condition specified in the php code is true, then one of them gets selected/checked by default but the accompanying hidden inputs from the onchange function are not displayed until the selection is changed.
N:B - The value of $mode is retrieved from a database.
You can trigger onchange programmatically, for ex., with element.onchange();.
function conditionalDisplay(value) {
// Let's for example log to browser console
console.log('Do something useful with ' + value);
}
// When DOM is ready, trigger an `onchange` event
document.addEventListener('DOMContentLoaded', function() {
var singleElement = document.getElementById('single');
var multiElement = document.getElementById('multi');
// Test which exactly element is checked
console.log(`singleElement.checked: ${singleElement.checked}`);
console.log(`multiElement.checked: ${multiElement.checked}`);
if (singleElement.checked == true) {
singleElement.onchange();
} else {
multiElement.onchange();
}
});
<input name="mode" id="single" onchange="conditionalDisplay(this.value)" type="radio" value="single">
<input name="mode" id="multi" onchange="conditionalDisplay(this.value)" type="radio" value="multi" checked>
This one might be useful for you as well How can I trigger an onchange event manually?
I'm building an ecommerce website with 100 items. Each item has an item option (i.e. Small, Medium, Large). Each option has a value with an integer that identifies the option.
When the user clicks "Add to Cart," I need express that value as a variable. The problem is all of these items have the same exact class/id so I can't write an onclick function for each one.
How can I use jQuery to get the selected option value onclick without a class/id to identify it?
Basic structure of the item form:
<form>
<label>First Item</label>
<select>
<option value="6432">Large</option>
<option value="5332">Small</option>
</select>
<input type="submit" value = "Add to Cart">
</form>
Here's a Fiddle that shows what I'm talking about: http://jsfiddle.net/cusygh4o/
Thanks :-)
Try this:
$('input[type="submit"]').on('click', function(e) {
e.preventDefault();
alert($(this).prev('select').val());
});
Updated JSFiddle: http://jsfiddle.net/cusygh4o/1/
Note: if there is anything you can do to narrow down that 'input[type="submit"]' selector, you should. For example, if you have a parent element with an id, you could do something like '#shopping-items input[type="submit"]'.
jsFiddle Demo
Just base it off where the click occurred.
$("input[type=submit]").click(function(){
alert($(this).parents("form").find("select").val());
});
Use this
jQuery(document).ready(function(){
var selectedValue;
$('input[type="submit"]').on('click', function() {
selectedValue=jQuery('form select').val();
alert(selectedValue);
})
})
Lots of different ways to go about it: http://jsfiddle.net/cusygh4o/2/
$('form').on('submit', function(e) {
alert($(this).find('select').val());
});
Try this
<script>
function getValue(e){
value = e.closest('form').find('select').find(":selected").text();
alert(value);
}
</script>
Then replace all your <input type="submit" value = "Add to Cart"> with <input onclick="getValue($(this))" type="submit" value = "Add to Cart">
I am wondering if there is a way to reset a radio to it's originally selected option. I know of defaultValue for inputs but is there a way to make it so that I can reset the radios back to their originally selected value on page load?
I am not wanting to simply unselect all radios. I am trying to put them back to their originally selected value.
Thanks for any info.
Yes, radio inputs do have defaultValue property, but what you are looking for is the defaultChecked property:
$('input[type=radio]').prop('checked', function() {
return this.defaultChecked;
});
That being said, if you want to reset the form you can use the reset method of the HTMLFormElement object:
$('#formElement').get(0).reset();
I think you want this
<form action="">
<input type="radio" name="gender" value="male" checked="true"/>Male
<input type="radio" name="gender" value="female"/>Female
<input type="reset" value="reset"/>
</form>
Any time you will reset the form, the male radio button will be selected.
I will rather make a jQuery plugin like this:
$.fn.defaultVal = function (checked) {
if(checked === true || checked === false) {
$(this).attr("data-default", checked);
return;
}
if(!$(this).attr("data-default")) {
console.log("No default value assigned!");
return;
}
return $(this).attr("data-default");
}
JSFIDDLE LINK UPDATE
Working Demo is here: JSFIDDLE
I'm trying get a form to fill in inputs automatically when a user puts in information in the footage field which should then be plugged into an equation with JQuery and then the answer should be output in postQuantity. Since the user can add inputs the form is set up that each footage should go with a corresponding postQuantity signified by its suffix number. So that footage2 should be used to find postQuantity2 and 3 for 3 and so on. The problem is that only the first field is automatically filling in and that anytime a different footage class is changed nothing happens. Any insight on where I went wrong and advice on how to fix it will be greatly appreciated! Thanks! Here is a JSFiddle - http://jsfiddle.net/gv0029/TwH5n/
HTML:
<form>
<fieldset id="fence">
<div class="inputFence">
<fieldset class="fenceDescripton">
<legend><strong>Fence Description</strong></legend>
<label>Footage<input name="footage_1" class="footage" /></label>
<select name="fenceHeight_1" class="fenceHeight">
<!--got rid of "select" from the value. not needed at all-->
<option value="">Select Fence Height</option>
<!--got rid of the ids completely. the numbers from the values are all you need-->
<option value="6">6 Ft.</option>
<option value="8">8 Ft.</option>
</select>
</fieldset>
<fieldset class="post">
<legend><strong>Post Type</strong>
</legend>
<label>Post Quantity:
<input type="postQuantity" name="postQuantity_1" class="postQuantity" value="" />
</label>
<select name="postMeasurements_1" class="postMeasurements">
<option value="">Select Post Measurements</option>
<option value="23/8 x .065 x 8">2 3/8 x .065 x 8</option>
<option value="23/8 x .095 x 8">23/8 x .095 x 8</option>
</select>
</fieldset>
</div>
</fieldset>
<div>
<input type="button" id="btnAddFence" value="Add Another Fence" />
<input type="button" id="btnDelFence" value="Remove Fence" />
</div>
</form>
JS:
//Quantity for Posts
$("[class^='footage']").bind('keypress keydown keyup change', function(){
var footage = parseFloat($(this).val(),10);
var total = '';
var parts = $(this).attr('name').split("_");
var fenceNumber = parts[1];
if(!isNaN(footage)){
total = Math.ceil(footage /7);
$(":input[name='postQuantity_" + fenceNumber + "'" + ']').val(total.toString());
} else {
$(":input[name='postQuantity_" + fenceNumber + "'" + ']').val("");
}
});
//Dynamic Fence Input Fields
$('#btnAddFence').click(function () {
// create the new element via clone()
var newElem = $('.inputFence:last').clone();
// insert the new element after the last "duplicable" input field
$('.inputFence:last').after(newElem);
// enable the "remove" button
$('#btnDelFence').removeAttr('disabled');
//get the input name and split into array (assuming your clone is always last)
var parts = $('.fenceHeight:last').attr('name').split("_");
//change the second element of the array to be one higher
parts[1]++;
//join back into a string and apply to the new element
$('.fenceHeight:last').attr('name', parts.join("_"));
//do the same for other two inputs
parts = $('.postQuantity:last').attr('name').split("_");
parts[1]++;
$('.postQuantity:last').attr('name', parts.join("_"));
parts = $('.postMeasurements:last').attr('name').split("_");
parts[1]++;
$('.postMeasurements:last').attr('name', parts.join("_"));
parts = $('.footage:last').attr('name').split("_");
parts[1]++;
$('.footage:last').attr('name', parts.join("_"));
// business rule: you can only add 5 names
//if (newNum == 5)
//$('#btnAdd').attr('disabled','disabled');
});
$('#btnDelFence').click(function () {
//remove the last inputFence
$('.inputFence:last').remove();
// if only one element remains, disable the "remove" button
if ($('.inputFence').length == 1) $('#btnDelFence').attr('disabled', 'disabled');
});
$('#btnDelFence').attr('disabled', 'disabled');
I think you want somethign like this:
http://jsfiddle.net/TwH5n/3/
the line I changed was:
$(document.body).on('keydown', '[class^="footage"]'
this binds the event to all future '[class^="footage"]' elements
ideally you would not do this on body since its not efficient. find a closer parent, or attach the event to each clone upon creation.
The jsfiddle is wrong
Anyway, you are using .bind method which is bind event handlers to currently existing elements. You can use .live method which is working for selector instead of elements, but this is deprecated in version 1.7, and removed in 1.9
As of http://api.jquery.com/bind/
For more flexible event binding, see the discussion of event
delegation in .on() or .delegate().
Hope this helps
P.S. Right example without using deprecated methods
$('form').on('keypress keydown keyup change',"[class^='footage']", function(){});
http://jsfiddle.net/TwH5n/7/
I am building a dynamic form in that the user can keep adding entries until they satisfied, to do this, I use this javascript, to pull in some html,
$('#add_another').click(function(e){
$.get('/admin/add_grade_course', function(data) {
$('#added_by_ajax').append(data);
});
e.preventDefault();
});
The HTML that is returned is a follows,
<fieldset>
<select name="course_type">
<option value="Classroom based learning">Classroom Based Learning</option>
<option value="Apprenticeship based learning">Aprenticeship Based Learning</option>
<option value="On the Job Learning">On The Job Learning</option>
</select>
<label for="course_names">Course Name</label>
<input type="text" name="course_names" value="<?php set_value('course_names');?>"/>
<?php echo form_error('course_names'); ?>
<label for="course_links">Course Links</label>
<input type="text" name="course_links" value="<?php set_value('course_links');?>"/>
<?php echo form_error('course_links'); ?>
<label for="grade_desc">Description of Grades Needed</label>
<textarea name="grade_desc"><?php set_value('grade_desc')?></textarea>
Delete
</fieldset>
My question is that as you can see there is nothing unique about the entry form that is created on the fly, if the user has added a new entry field and then decides they dont need it, how would I go about removing the last added form elements?, I assume I need to somehow get the parent fieldset for the clicked .remove_fields link? How would I do that, without selecting all the fieldsets on the page?
Use the closest-method:
// Add a delegated click-handler for clicks on remove-links
$('body').delegate('a.remove_fields', 'click',
// In the event handler, remove the fieldset this link belongs to
function (e) {
// this refers to the link that was clicked.
// closest traverse the DOM upwards until it finds an ancestor
// matching the selector. (i.e. a fieldset).
// After we find this ancestor, we remove it from the DOM.
$(this).closest('fieldset').remove();
}
);
The following will bind to the click event using the live() function and remove the selected entry. The live function is handy because it means that any dynamically added markup that matches the selector will have the function bound as it is added. This means that each time the user clicks the add_another link, the newly returned fieldset has the function bound to the click event of its remove_fields link.
$(function(){ //shorthand for $(document).ready(function(){
$('.remove_fields').live('click', function() {
//$(this).parent() returns the current fieldset, remove() removes it.
$(this).parent().remove();
});
});
Something like this might work:
var form_counter = 0;
$('#add_another').click(function(e){
$.get('/admin/add_grade_course', function(data) {
$(data).attr('id', 'form_' + form_counter);
var form_count_ref = form_counter;
$('a:last', data).onclick(function(){
$('form_' + form_count_ref).remove();
});
form_counter++;
$('#added_by_ajax').append(data);
});
e.preventDefault();
});