jQuery data attribute updates only after second click - javascript

I have this jquery code which should print all selected checkboxes:
$('.engagement-type').on('click', function () {
var engagementTypes = $('.engagement-type').parent().find('[data-checkbox="checked"]');
console.log(engagementTypes);
});
12 checkboxes are in the table:
<td>
<input name="EngagementTypes[0].EngagementTypeId"
id="EngagementTypes_0__EngagementTypeId"
type="hidden" value="1" data-val-required="The Engagement field is required."
data-val="true" data-val-number="The field Engagement must be a number.">
<span class="pull-left">
<div class="engagement-type" data-checkbox="checked">
<input name="EngagementTypes[0].IsSelected"
id="EngagementTypes_0__IsSelected" type="checkbox" value="true"
data-val-required="The IsSelected field is required."
data-val="true">
<input name="EngagementTypes[0].IsSelected" type="hidden" value="false">
</div>
</span>
Audit
</td>
After first click on the checkbox I get empty list of selected engagement types. The first checkbox appears only after the second checkbox is checked. Why is that?

var engagementTypes = $('.engagement-type').parent().find('[data-checkbox="checked"]')
This will only work if you click on the div engagement-type. But if you click on one of the checkboxes in the div the parent is the one with the checkbox attribute, so he will not find another within this.
So you should always select
var elementYouWant = $('.engagement-type')
Then check if the data attribute is checked.
var dataElement = elementYouWant.data();
if (dataElement['checkbox'] == "checked") {
console.log("Oh yeah baby")
}
Ofcourse if there are multiple, you should do this in a loop for each of them.

As #T.J. Crowder mentioned, there must be additional code which you do not have provided.
At least the part which will set the data-checkbox = checked.
I would assume to use the checkbox state itself like:
$('.engagement-type').on('click', function () {
var engagementTypesChecked = $('.engagement-type').parent().find('input[type="checkbox"]:checked');
console.log(engagementTypesChecked);
});

Related

Trying to disable div section of form only if the values of 2 fields are 1 and checked

I am trying to disable a section of a form if it has been signed by a supervisor using 2 fields.
The problem is it works too good. It disables the section on a new form. For brevity here are the 2 fields, the hidden values of those fields and the jquery script.
This is the code of the fields when adding a new form or record.
These 2 forms are within the div with the id supersection.
Here is the html for the 2 fields
First the hidden values of the fields in the form then the html of the fields themselves.
<div id="supersection" style="border: none;">
<input type="hidden" name="supersignoff" value="0"/>
<input type="hidden" name="superdeclare" value="0"/>
<label class="padd2left" for="supersignoff">
<input type="checkbox" value="1" id="supersignoff" name="supersignoff" />
Complete and sign</label>
<label for="superdeclare">
<input type="checkbox" value="1" id="superdeclare" name="superdeclare" />
I have completed with the best info from all parties</label>
Below is the jquery script. This disables the whole section.
$(function(){
var signoff = $("#supersignoff").val();
var sdeclare = $("#superdeclare").val()
if(signoff=="1" && sdeclare=="1"){
$("#supersection *").prop("disabled",true);
}
})
Again the section is being disabled even when it is a new form.
Any ideas?
$(function(){
var signoff = $("#supersignoff").prop('checked');
var sdeclare = $("#superdeclare").prop('checked')
if(signoff && sdeclare){
$("#supersection *").prop("disabled",true);
}
});
.prop('checked') will give you the status of checkbox is checked or not, but not .val().
Ref: .prop() and .val()

Adding ID to button, but must change based on radio input selection

EDITED TO ADD HTML: not exactly the same since im not in my office anymore, but you'll get the idea.
The scenario is i have a part of a site where users can pick 1 of multiple addresses they have saved. The ID gets generated for each address and I need to apply that ID to a button to submit the form.
I've gotten it so the button receives the ID from the first click, but if I try to select a different address, the ID will not switch. How can I have the button use the ID of the most recently selected radio input? I'm using a data attribute to select this.
HTML:
<div>
<form>
<input type="radio" data-js="select" id="Test123" /> (id created dynamically)
<label>Address 1</label>
<input type="radio" dat-js="select" id="Test124" /> (id created dynamically)
<label>Address 2</label>
</form>
</div>
<button class="address-continue">Continue</button>
var radioID = $('*[data-js]').attr('id');
var addrContinue = $('.address-continue');
$('*[data-js]').click(function () {
$(addrContinue).attr('id', radioID);
});
Scenario: user clicks on address 1, so ID is then placed on the button for address 1. user made a mistake, meant to click on address 2. currently when i click address 2, the ID on the button doesn't change. it remains the same as the original click.
I need the ID on the continue button to change based on the proper radio selection.
Since id is unique use class
$('*[data-js]').click(function () {
var addrButton = $('.address-continue');
addrButton.removeClass(test123);
addrButton.removeClass(test124);
radioID = $('*[data-js]').attr('id');
addrButton.addClass(radioID);
});
Also your basic problem might be because you did not collect your radioID in ur radio function hence it wasn't updated so try this
$('*[data-js]').click(function () {
var radioID = $('*[data-js]').attr('id');
$(addrContinue).attr('id', radioID);
});
The following should do it for you hoping the corresponding elements are in the same order:
$('[data-js]').on('change',function() {
$('.address-continue').data('id', this.id);
});
$('.address-continue').on('click',function() {
alert( $(this).data('id') );
});
You cannot assign a second element in your document the id of another. IDs should be unique; therefore I have used data-id.
$('[data-js]').on('change',function() {
$('.address-continue').data('id', this.id);
});
$('.address-continue').on('click',function() {
alert( $(this).data('id') );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<form>
<input type="radio" name="address" data-js="select" id="Test123" /> (id created dynamically)
<label>Address 1</label>
<input type="radio" name="address" data-js="select" id="Test124" /> (id created dynamically)
<label>Address 2</label>
</form>
</div>
<button class="address-continue">Continue</button>

How to rename a html form elements' Id attribute using Jquery?

I have a form which contains radio boxes.
<input type="radio" name="categoryid" id="category420" value="420" onclick="checkCategory();" > Category1
<input type="radio" name="categoryid" id="category1314" value="13,14" onclick="checkCategory();" >Category2
<input type="radio" name="categoryid" id="category594" value="594" onclick="checkCategory();" >Category3
When the radio elements value attribute is a comma separated list (13,14) I need the elements Id attribute to change.
In the example above, when the second category is selected then "CategoryIDs=13,14" should be passed to the action page not categoryid. But for the other two categories it should pass categoryid value.
I cannot edit the action page.
The question: How can I change the radio buttons Id attribute in JQuery?
Change the Id
Based on your requirement to have only one Id (categoryid/s) then you could change the Id using JQuery, before the form is submitted.
JSFiddle working example - http://jsfiddle.net/daTYY/
JQuery
$(function() {
$('input:radio[name=categoryid]').change(function() {
if ($(this).val().indexOf(",") >= 0) {
$(this).attr("id","newId");
}
});
});
Update a hidden input
Add a hidden input named categoryids. Then use JQuery to check if categoryid contains a comma and if it does populate categoryids with the value.
JSFiddle working example - http://jsfiddle.net/KVs79/
HTML
<input type="radio" name="categoryid" id="categoryid1" value="13,14" />Category2
<input type="radio" name="categoryid" id="categoryid2" value="404" />Category3
<input type="hidden" name="categoryids" id="categoryids" value="" />
JQuery
$(function() {
$('input:radio[name=categoryid]').change(function() {
if ($(this).val().indexOf(",") >= 0) {
$("#categoryids").val("13,14");
}else{
$("#categoryids").val("");
}
});
});

Checking a different checkbox hides input field

I have an input field that only shows when the option "Other" is checked. The input field fades out when I uncheck the "Other" checkbox, but I would also like the input field to fade out say if, instead of unchecking the "Other" checkbox I check another checkbox of the same group. Therefore, the "Other" input field should not be visible unless "Other" is checked. I have the javascript partially working, but when I check another checkbox the "Other" input field stays visible.
HTML
<input type="checkbox" id="residence_check" name="found"/>
<label for="residence_check">
Residence
</label>
<input type="checkbox" id="tradeshow_check" name="found"/>
<label for="tradeshow_check">
Tradeshow
</label>
<input type="checkbox" id="office_check" name="found"/>
<label for="office_check">
Office Building
</label>
<input type="checkbox" id="check_other" value="found_other" name="found"/>
<label for="check_other">
Other
</label>
<input type="text" id="check_input" placeholder="Other"/>
Javascript
$('#check_other').change(function() {
if($(this).is(":checked")) {
$('#check_input').fadeIn();
} else {
$('#check_input').fadeOut('fast');
}
});
From what I gather from your use case is that you don't want to use checkboxes, but radio buttons. If that is the case, this would be a good way to implement what you want:
http://jsfiddle.net/AeP58/1/
$('input[type=radio]').on('change', function() { //event on all radio buttons
if($(this).attr('id') == 'check_other' && $(this).prop('checked')) {
$('#check_input').fadeIn();
} else {
$('#check_input').fadeOut('fast');
}
});
If you do want checkboxes, you could change the code a bit and probably get what you want.
If you want to have some fun with checkboxes you could try this:
function showHideOtherInput() {
console.log($(this)[0]==$('#check_other')[0]);
var shouldShow=$('[id$="_check"]:checked').length===0 && $('#check_other').prop('checked');
console.log(shouldShow);
if(shouldShow) {
$('#check_input').fadeIn();
} else {
$('#check_input').fadeOut('fast');
}
}
$('#check_input').hide(); //since nothing is selected at this point just hide the input
$('#check_other').change(showHideOtherInput);
//for each XXXX_check checkbox trigger the show or hide function
$('[id$="_check"]').each(function(ix,el){$(el).change(showHideOtherInput)});
Hope this works for you.
:)

How can I show input fields only when previous input has a valid value?

I have a form that requires between 3 and 10 text input items. When the form first loads it will show 3 inputs (minimum).
I'd like to efficiently show input rows as the previous row has a valid value (let's assume greater than 3 characters for example). So if you fill out the first 3, you will automatically see a 4th optional input row.
Can you help me loop through this quick list efficiently in jQuery?
HTML:
<input type="text" class="item_1" name="item_1">
<input type="text" class="item_2" name="item_2">
<input type="text" class="item_3" name="item_3">
<input type="text" class="item_4" name="item_4">
<input type="text" class="item_5" name="item_5">
<input type="text" class="item_6" name="item_6">
<input type="text" class="item_7" name="item_7">
<input type="text" class="item_8" name="item_8">
<input type="text" class="item_9" name="item_9">
<input type="text" class="item_10" name="item_10">
CSS:
.item_4,.item_5,.item_6,.item_7,.item_8,.item_9,.item_10 { display:none }
This is pretty simple - you shouldn't even need a loop if you let jQuery's chaining do the work. I'd do something like:
$("#myform input").change(function(){ //If an input in your form is changed,
if ($(this).val() == 42){ //replace with your validation logic :)
$(this).next('input').show(); //This shows the next sibling element to the triggering element
} else { //but if it fails validation...
$(this).nextAll('input').hide().val(""); //hide them and delete the contents to stop the form from uploading invalidated data!
}
});
This does what you asked, and for bonus points it hides and empties later boxes if their predecessors are later changed to be invalid.

Categories

Resources