Unable to check a checkbox via javascript - javascript

I have a form on a page, with a checkbox input field. I also have a table on the page with a column that has true/false values. Each row in the table also has a checkbox with id="selectedReviewTypeYear". There is also a button with id="getDataToEdit".
When the getDataToEdit button is clicked, the javascript checks to see if any id="selectedReviewTypeYear" boxes are checked. If a box is checked, a div is opened up with form fields prepopulated based on the row selected. If no boxes are checked, the div remains hidden.
My problem is that the checkboxes aren't getting checked when the table data is "true." Here is the javascript:
$('#getDataToEdit').on('click', function (){
$('#reviewTypeTable').find('tr').each(function (){
var row = $(this);
if (row.find('input[id="selectedReviewTypeYearID"]').is(':checked')){
var idx = table.row(this).index();
var vReviewName = document.getElementById("editReviewTypeYear-name");
var vAllowMultiple = document.getElementById("allowMultiple");
var vAllowMultipleSpan = document.getElementById("allowMultipleSpan");
vReviewName.innerHTML = table.cell(idx, 2).data();
if (table.cell(idx, 3).data() == "true"){
$("#allowMultiple").prop("checked", true);
vAllowMultipleSpan.innerHTML = table.cell(idx, 3).data();
}
else {
$("#allowMultiple").prop("checked", false);
vAllowMultipleSpan.innerHTML = table.cell(idx, 3).data();
}
showHide.style.visibility = 'visible';
}
})
});
For testing purposes, I added a span element to the form called allowMultipleSpan. This was simply so I could see if the javascript is able to read the data in the table field, which it is. When I select a row, then click the button, the div opens up with the vReviewName.innerHTML populated correctly as well as the allowMultipleSpan populated correctly. However, the checkbox is not getting checked if the data is "true".
I am running JQuery 2.1.1. So far, I have tried using the following variations of the script, all with the same result:
From the JQuery (1.6+) spec:
$("#allowMultiple").prop("checked", true);
From the jQuery (1.5-) spec:
$("#allowMultiple").attr("checked", true);
From the Javascript spec:
document.getElementById("allowMultiple").checked = true;
Here is the HTML for my form:
<div class="widget-header"><h3>Edit: <span id="editReviewTypeYear-name" style="color: blue"></span></h3></div>
<div class="widget-content">
<form id="editReviewTypeYear-form" class="form-horizontal" url="submitReviewTypeYear.htm">
<div class="form-group">
<label class="col-sm-2 control-label">Allow Multiple: </label>
<div class="col-sm-10">
<input type="checkbox" id="allowMultiple" name="allowMultiple" />
<span id="allowMultipleSpan" style="color: blue"></span>
</div>
</div>
<div class="form-actions">
<button id="submitReviewTypeYear" type="submit">Save</button>
<button class="btn btn-small btn-warning reg-cancel" id="submitReviewTypeYear-cancel" type="button" name="Cancel" value="cancel">Cancel</button>
</div>
</form>
</div>

Have you tried if (table.cell(idx, 3).data() == true)?
You were always getting the false condition because you were comparing a boolean with "true" as a string.

Related

Checkbox click is not working in safari for the first time

The delete button is disabled when the page load. There are multiple checkboxes on the form and when a user clicks a checkbox then the delete button change to enable. When a user unchecks the checkbox (didn't select any checkbox) then the delete button change to disabled. Also, all the selected checkbox value will be assigned to an input field separated by a comma.
Below code is working fine in chrome. But it's not working fine in Safari. In Safari user need to check, uncheck again they have to check (third time) or when they select the second checkbox then only the delete button change to enabled and the selected value is displaying in the input field. I don't know whats wrong with this code.
Please check this demo in Chrome and Safari you will get it.
DEMO
$(document).on("click", ".imgtitleclick", function (e) {
$checks = $('.imgtitleclickmodal');
$checks.on('change', function() {
var string = $checks.filter(':checked').map(function(i,v){
return this.value;
}).get().join(',');
$('.hiddenimgnumdis').val(string);
$('.hoverforport-img-del').prop('disabled', $checks.filter(':checked').length < 1);
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<button class="btn-danger hoverforport-img-del floatright" disabled data-toggle="modal" data-target="#confirm-delete-portfolio">Delete</button>
<ul class="photo-grid lightgalleryselector">
<div class="col-sm-4 col-xs-6 col-md-3 col-lg-3 shw mblpad hoverforport-img">
<label class="width100 editbtnprofilea nopadd posabsol imgtitleclick color5" for="1">
<input type="checkbox" value="1" class="imgtitleclickmodal" id="1">
</label>
</div>
<div class="col-sm-4 col-xs-6 col-md-3 col-lg-3 shw mblpad hoverforport-img">
<label class="width100 editbtnprofilea nopadd posabsol imgtitleclick color5" for="2">
<input type="checkbox" value="2" class="imgtitleclickmodal" id="2">
</label>
</div>
</ul>
<input type="text" class="hiddenimgnumdis"/>
Looks like you're binding the change event multiple times (anytime .imgtitleclick is clicked). It's also going to do it for all .imgtitleclickmodal because you haven't scoped it to the current checkbox... here's an example that is working for me:
$(document).on("click", ".imgtitleclick", function (e) {
$(this).find('.imgtitleclickmodal').trigger('change');
});
$(document).on("change", ".imgtitleclickmodal", function (e) {
var $checks = $('.imgtitleclickmodal');
var string = $checks.filter(':checked').map(function(i,v){
return this.value;
}).get().join(',');
$('.hiddenimgnumdis').val(string);
$('.hoverforport-img-del').prop('disabled', $checks.filter(':checked').length < 1);
});

Input Box Values Disappear on Button Click

I am just starting out with JQuery for asp.net core mvc.
I have a section of a page comprising a list of items linked to the main subject. When an 'edit' button is clicked against one of the list items, a hidden section (fieldset) is displayed and populated with the values of that list item. Other inputs on the page are disabled and the user can edit the item. All works fine.
However, when finished editing, the user clicks a 'submit' button (within the previously hidden fieldset) and the idea is to submit the edited data via ajax and, if accepted, to update the list. Ajax, etc. is not (yet) the problem.
When the user clicks the 'submit' button (coded as type="button"), the values in the edited section appear to have been cleared and are returned as spaces or nulls. It only seems to apply to this fieldset, as (disabled) values from the remainder of the document can be retrieved (just for testing purposes).
Can anyone tell me what is going on here and how to preserve these edited values, please?
#**** Drop-down section for editing Admissions ****#
<fieldset id="AdmissionsEditFieldset" class="app-edit-main-fieldset" hidden>
<legend id="AdmissionsEditLegend" class="app-edit-fieldset-legend">Editing Admission</legend>
<div class="row">
<div class="col-sm-12" style="padding-left: 5%; padding-right: 5%">
<div class="form-group">
<strong><label>Institution:</label></strong>
<span class="app-label-to-input-sep">
<input id="admId" name="aId" type="text" class="form-input app-can-disable" asp-for="Admission.Id" hidden />
<select id="admPlace" name="aPlace" type="text" class="app-can-disable" asp-items="Model.PlaceOfDetentionDd" asp-for="Admission.PlaceId"></select>
</span>
<strong><label class="app-input-fld-sep">Date Admitted:</label></strong>
<span class="app-label-to-input-sep">
<input id="admDate" name="aDate" type="text" class="form-input app-can-disable" asp-for="Admission.DateAdmitted" style="width: 5%" />
</span>
<strong><label class="app-input-fld-sep">Sequence:</label></strong>
<span class="app-label-to-input-sep app-can-disable">
<input id="admSeq" name="aSeq" type="text" class="form-input" asp-for="Admission.Seq" style="width: 5%" />
</span>
<span>
<button id="admSubmitBtn" class="btn btn-sm btn-primary app-adm-edit-btn" type="button">Submit</button>
<button id="admCancelBtn" type="button" class="btn btn-sm btn-danger app-button-to-button-sep">Cancel</button>
</span>
</div>
</div>
</div>
<div class="row">
<div class="col-sm-12" style="padding-left: 5%; padding-right: 5%">
</div>
</div>
And this is the JavaScript/JQuery
$(document).ready(function () {
$('.app-adm-edit-btn').click(function (event) {
//*** Prevent default button actions
event.preventDefault();
// btn has format 'editN[N...]'
var btn = event.target.id;
var sid = btn.substring(4);
//*** Un-hide the editing drop-down
$('#AdmissionsEditFieldset').removeAttr('hidden');
//*** Copy values from the relevent line in the table to the editing drop-down
$('#admId').val($('#ident' + sid).text());
$('#admPlace').val($('#placeN' + sid).text());
$('#admDate').val($('#dateAdm' + sid).text());
$('#admSeq').val($('#seq' + sid).text());
//*** Set the section legend
$('#AdmissionsEditLegend').text('Editing an Admission');
//*** Disable other sections
DisableFieldsets(); // Works OK - makes no difference if commented out
//*** Focus the first input box
$('#admPlace').focus();
}); // $('.app-adm-edit-btn').click
/*----------------------------------------------------------------------------------
Admissions Submit button click handler
----------------------------------------------------------------------------------*/
$('#admSubmitBtn').click(function (event) {
//*** Prevent default button actions
event.preventDefault();
// Just to verify nothing wrong with JSON.stringify
var id = $('#admId').val();
var placeId = $('#admPlace').val();
var seq = $('#admSeq').val();
var dateAdmitted = $('#admDate').val();
var court = $('#Court').val();
// Not integrated, so that I can display the values
var jsn = JSON.stringify({
Id: $('#admId').val(),
PlaceId: $('#admPlace').val(),
Seq: $('#admSeq').val(),
DateAdmitted: $('#admDate').val()
});
$.ajax({
url: "api/EditAdmissionApi",
method: "POST",
contentType: "application/json",
data: jsn,
success: function (data) {
alert("Ajax Success"); //TODO
}
});
alert(jsn);
//TODO
});
/*------------------------------------------------------------------------
Admissions Cancel button click handler
--------------------------------------------------------------------------*/
$('#admCancelBtn').click(function (event) {
//*** Prevent default button actions
event.preventDefault();
});
}); // $(document).ready
/*===========================================================================
Helper Functions
===========================================================================*/
/*---------------------------------------------------------------------------
DisableFieldsets Helper function to disable fieldsets while input of linked
items takes place
---------------------------------------------------------------------------*/
function DisableFieldsets() {
DoDisableFieldsets('#MainFieldset');
DoDisableFieldsets('#AdmissionsFieldset');
DoDisableFieldsets('#ChildrenFieldset');
DoDisableFieldsets('#SubmitButtonsNonFieldset');
}
function DoDisableFieldsets(id) {
var xId = $(id);
$('.app-can-disable', xId).attr('disabled', 'disabled');
$(xId).addClass('app-disabled-background');
}
Yes it does and many thanks for the suggestion, mj.
Trying to see why and testing alternatives brought me to the real issue, however. I have to confess that it was one of those stupidities that you can stare at for hours without seeing. Still I will confess, in case it helps anyone else.
I had given the Edit buttons in the list a 'dummy' class name to make selection easier. Then I had inadvertently copied and adapted the button html to be the Submit button following edit, without deleting the class. So both the Edit and Submit button handlers seemed to be called, which was causing havoc (I have not yet worked out why this was not just producing the unedited text in the second handler - but life's too short). So a dumb question on my part - sorry for wasting everyone's time.
The construct $('#admId').val($('#ident' + sid).text()); works fine now.

Varying modal content based on trigger with input: radio and checkbox

I am using Net mvc4 in this project. I got a problem in my javascript where the
modal.find('modal-body input:radio[name=require_attachment][id=' + attachment+ ']').prop('checked', true);
It does not function properly. I also tried the jquery filter function:
modal.find('modal-body input:radio[name=require_attachment]').filter(['value=' + attachment+ '']).prop('checked', true);
Which has the same result, not working.
In my modal button that has data-* on with.e.g. data-attachment, I want to display it as a radio checked whether what value it return to the content of my modal.
<button type="button" class="btn btn-primary"
data-toggle="modal"
data-target="#Update_COA_Codes"
data-code="#item.code"
data-attachment="#item.require_attachment"
data-status="#item.status"
data-description="#item.description">Edit</button>
Inside my jquery script:
$('#Update_COA_Codes').on('show.bs.modal', function (event) {
var button = $(event.relatedTarget)
var attachment = button.data('attachment');
//... other code here
var modal = $(this);
modal.find('modal-body input:radio[name= require_attachment]')
.filter(['value=' + attachment + ''])
.prop('checked', true);
});
HTML modal-body
<div class="row top-buffer">
<div class="col-md-4">
<label><span class="red">*</span>Needs Attachments?</label>
</div>
<div class="col-md-4">
<input type="radio" name="require_attachment" value="true"> Yes
<input type="radio" name="require_attachment" value="false"> No
</div>
</div>
I'm not sure if this is the correct way of doing it. I'm open for any suggestions, thank you.

Not able to get value When disable a Div tag

I have designed a page using MVC Razor. In which I had a div such that is following
<div class="row" id="DivDisableForView">
<div class="col-md-4">
<label for="" class="control-label">
Product
</label>
<br />
#Html.DropDownListFor(m => m.ProductSeq, Model.products.ToSelectListItems(x => x.ProductName, x => x.Id.ToString(), "", true, "", "Select"), new { #class = "form-control" }).DisableIf(() => Model.IsReadOnly == true || !Model.IsAdd)
#Html.HiddenFor(m => m.ProductSeq)
</div>
<div class="col-md-4" runat="server">
<b>Exception Type</b>
<br />
#Html.EnumRadioButtonFor(m => m.enumExceptionType, true).DisableIf(() => Model.IsReadOnly == true || !Model.IsAdd)
#Html.HiddenFor(m => m.enumExceptionType)
</div>
<div class="col-md-4" id="divTranMode">
<b>Transaction Mode</b>
<br />
#Html.EnumRadioButtonFor(m => m.enumTransactionMode, true).DisableIf(() => Model.IsReadOnly == true || !Model.IsAdd)
#Html.HiddenFor(m => m.enumTransactionMode)
</div>
</div>
if (Model.IsAdd)
{
<div class="row" id="ViewButton">
<button id="btnView" name="Submit" class="btn btn-default">
View
</button>
</div>
}
...
...
...
If I click the view button,then a grid will load based on the above given field's data and also disabled the fields like following,
$("#DivDisableForView").prop('disabled', true);
After that, When I click the submit button, then the disabled field's data is not present, (i.e) The values are null. So how to avoid it or how to disable a div tag without its value get null or empty.Please anybody help
Html elements with disabled="true" attribute are not going to be sent over in form data. You can just hide the div, and the data will still be sent for processing. Use:
$("#DivDisableForView").hide();
EDIT
No, I want to show the fields in the screen
In case you want to keep the fields visible, you could try to set them to readonly.
Something like:
$('#DivDisableForView input').attr('readonly', 'readonly');
//maybe also set color to gray
$('#DivDisableForView input').css("background-color", "#eee");
Readonly attributes are still going to be sent over in form data.
EDIT 2
Solution for select fields:
This JS would solve the select problem:
$('#DivDisableForView input, #DivDisableForView select').attr('readonly', 'readonly');
//maybe also set color to gray
$('#DivDisableForView input, #DivDisableForView select').css("background-color", "#eee");
//selects
$('#DivDisableForView select').attr('onfocus', 'this.defaultIndex=this.selectedIndex;');
$('#DivDisableForView select').attr('onchange', 'this.selectedIndex=this.defaultIndex');
Here is a JSFiddle of it: https://jsfiddle.net/ddan/W4Km8/5340/
Hope it helps.
EDIT 3
For radio and checkbox you can do the following:
$('#DivDisableForView :radio, #DivDisableForView :checkbox').click(function() {
return false;
});
See example (updated JSFiddle): https://jsfiddle.net/ddan/W4Km8/5341/
Please hide your div instead of disabling.
Use this
$("#DivDisableForView").css('display', 'none');
OR
$("#DivDisableForView").hide();
use .hide() or apply using .css('display','none') , if you want to disable only, first get the value of the div and store it in a variable then disable the div.
var divvalue = $("#DivDisableForView").val();
$("#DivDisableForView").prop('disabled', true);

Radio buttons checked changing submit text

My site structure consists on an index.php which is styled by a css file. It then includes the following php code in a separate file:
<?php include("globals.php"); ?>
<form action="<?php echo $website.$relative_string;?>" name="subscribe" onsubmit="javascript:return checkEmail(this);" method="post">
<div id="cell8" class="titlecell2"><h3>Email:</h3></div>
<div id="cell9" class="inputcell2">
<input type="text" class="inputfield2" name="email" value="Your Email..." id="email2" maxlength="255" onfocus="this.value='';">
</div>
<div id="cell10" class="textcell3">
<input name="group" type="hidden" id="group[]" value="<?php echo $group; ?>">
<input name="subscribe" id="sub" type="radio" value="true" checked>
</span>Subscribe </p>
</div>
<div id="cell11" class="buttoncell">
<button type="submit" name="Submit2" value="Join" id="submitButton2">
<span>OK</span>
</button>
</div>
<div id="cell8" class="textcell4">
<input type="radio" name="subscribe" id="unsub" value="false">
</span>Un-Subscribe </p>
</div>
</form>
It appears on screen with no problems in the correct layout as my css style sheet. What I would like this to do is when I select the "Subscribe" radio button the submit button text "OK" changes to "Join". When I click on the Unsubscribe button text "OK" or "Join" changes to "Leave".
I tried to make some code from research:
if(document.getElementById('sub').checked) {
document.write("<span>Join</span>"
}
else if(document.getElementById('unsub').checked) {
document.write("<span>Leave</span>)
}
I think this kind of worked in that it changed to Join (replacing the OK line, but obviously didn't update on clicking unsubscribe. I guess it would update on refreshing the page if my default wasn't join. I guess I need to do some form of onclick but then I have no idea how to adjust that span ok bit.
Please help?
Many thanks Chris
Here is a solution in plain JavaScript without jQuery. It avoids the unnecessary overhead.
This should work, but I haven't had a chance to test it:
var sub = document.getElementById('sub'); // Save element to a variable, so you don't have to look for it again
var unsub = document.getElementById('unsub');
var btn = document.getElementById('submitButton2');
sub.onchange = function() //When sub changes
{
if(sub.checked) //If it's checked
{
btn.innerHTML = "<span>Join</span>"; // Set button to Join
}
else // If not..
{
btn.innerHTML = "<span>OK</span>"; // Set button to OK
}
}
unsub.onchange = function() //When unsub changes
{
if(unsub.checked) //If it's checked
{
btn.innerHTML = "<span>Leave</span>"; // Set button to Leave
}
else // If not..
{
btn.innerHTML = "<span>OK</span>"; // Set button to OK
}
}
However, you should not do it like this.
You should combine the two radio buttons into a radio group.
In that case you will listen for radio group to change, get the value of the radio group, set button text according to the value.
if you label your <span>OK</span> to something like <span id="your_id">OK</span> then added a class to your radio button like this <input class="your_class" type="radio" name="subscribe" id="unsub" value="false"> them...
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script>
$("#your_class").change(function () {
if ($(this).is(':checked')) {
$("#your_id").text('Join');
}else {
$("#your_id").text('Leave');
}
});
</script>
This was all written in the browser so let me know if there are any problems.

Categories