Why is my checkbox on change not working (AJAX) - javascript

This is how my razor code looks like
<form asp-action="Save" asp-controller="ClassesHeld" method="post">
<input asp-for="ClassHeldId" value="#Model.ClassHeldId" hidden />
<div class="form-group">
<label>Student</label>
<input asp-for="#Model.Student" value="#Model.Student" class="form-control" readonly />
</div>
<div class="form-group">
<label>Grade</label>
<input id="Grade"asp-for="Grade" type="number" value="#Model.Grade" class="form-control" min="0" max="5" />
</div>
<div class="form-group">
<label>Attendance</label>
<input id="Attendance" class="form-check-input" asp-for="Attendance" type="checkbox"/>
</div>
<button class="btn btn-primary" type="submit" value="Save">Save</button>
</form>
<script>
$("#Attendance").on("change", function () {
$("#Grade").attr("disabled", this.checked);
});
</script>
Yet for some reason, clicking on the checkbox does nothing at all. I have tried this with simple script as well, and that didn't work either.
document.getElementById('Attendance').onchange = function () {
document.getElementById('Grade').disabled = this.checked;
};
Neither of these worked.
I have even copied some solutions from here (one of them is that last simple scrip with document.getElementbyId, and none of it worked. I have to be missing something simple, but I've been looking at this for the past hour and I still can't figure it out.
I apologize if the question is stupid or noob-level. But I am getting desperate.
EDIT: Simply to add more information, this form works perfectly fine when submitting data, controller saves the stuff to the database... Everything works fine, just not the part where it disables the ability to edit the Grade if the student has not attended.
So the objective, is to disable the input field when the checkbox for "attendance" is checked

The .attr() method only manage string; So if you want to change an attribut like disabled or even checked with a boolean or something else, you have to use the prop method.
For more information check this post :
.prop() vs .attr()
You can execute the snippet below.
$("#Attendance").on("change", function () {
$("#Grade").prop("disabled", this.checked)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form asp-action="Save" asp-controller="ClassesHeld" method="post">
<input asp-for="ClassHeldId" value="#Model.ClassHeldId" hidden />
<div class="form-group">
<label>Student</label>
<input asp-for="#Model.Student" value="#Model.Student" class="form-control" readonly />
</div>
<div class="form-group">
<label>Grade</label>
<input id="Grade"asp-for="Grade" type="number" value="#Model.Grade" class="form-control" min="0" max="5" />
</div>
<div class="form-group">
<label>Attendance</label>
<input id="Attendance" class="form-check-input" asp-for="Attendance" type="checkbox"/>
</div>
<button class="btn btn-primary" type="submit" value="Save">Save</button>
</form>
<script>
</script>

I think you actually need to remove the disabled attribute when you don't want it. Maybe try this:
$(document).ready(function() {
$("#Attendance").on("change", function () {
if (this.checked) {
$("#Grade").attr("disabled", true);
} else {
$("#Grade").removeAttr("disabled");
}
});
});

Related

jQuery appending HTML elements out of order

I'll start this off by saying I use JS very infrequently, so this is likely a simple mistake. I came across the need to generate a form on the spot when a button is pressed. After some searching, I decided on using the append function from jQuery. Here is the code I wrote:
function replyToComment(commentId) {
var element = document.getElementById("reply-form");
if (element != null) {
element.remove()
}
const html = `
<div id="reply-form">
<label for="comment-form">Comment:</label>
<form method="post" id="comment-form" style="padding-bottom: 10px;">
<input type="hidden" name="csrfmiddlewaretoken" value="${csrf_token}"
<div class="form-group">
<div>
<textarea type="text" name="body" maxlength="1500" class="textarea form-control" cols="40" rows="10"></textarea>
</div>
</div>
<input type="text" name="comment-send" style="display:none;" readonly>
<input type="text" name="comment_id" value=${commentId} style="display:none;" readonly>
<button type="submit" class="btn btn-success">Send</button>
</form>
</div>`
$(`#${commentId}`).append(html)
}
When inspecting the final result, the argument passed into the append function is out of order:
I am not sure if the image will load in properly, but if it doesnt, its mostly irrelevant. Am I misusing the append function? Is there another way to do this that will handle the data I want to pass in properly?
It appears that you're neglecting to close one of your input tags.
You have:
<input type="hidden" name="csrfmiddlewaretoken" value="${csrf_token}"
This should be:
<input type="hidden" name="csrfmiddlewaretoken" value="${csrf_token}" />

How to $setdirty to a single input

I've got a little problem. I want to set to dirty a single input, I mean, because when I give a value automatically it stays in pristine class, doesn't change, and doesn't save the new value.
If I edit it, it works and change the class. I want to cancel that pristine class.
If anyone know please let me know.
<form class="form-horizontal" ng-repeat="studiant in studiants" name="form" id="form">
<input type="hidden" name="id" value="{{studiant.studiant_id}}" class="form-control" disabled>
<div class="form-group">
<label for="school" class="col-md-2 control-label">School</label>
<div class="col-md-1">
<input type="text" id="school" name="school" class="form-control" ng-init="studiant.school=studiant.studiant_school" ng-model="studiant.school">
</div>
</div>
<div class="form-group">
<label for="name" class="col-md-2 control-label">Student's Name</label>
<div class="col-md-10">
<input type="text" id="name" name="name" class="form-control" ng-init="studiant.name=studiant.studiant_name" ng-model="studiant.name">
</div>
</div>
</form>
And the script:
document.getElementbyId('name').value = "anything";
Or, if I doing wrong and I have to change the value with ng-model or something, please help me.
http://plnkr.co/edit/bVoljJqiK3CLB2xqZ6Zm?p=preview
You can see a working example there.
Make sure you have the name attr set for the form and the input.
HTML Example:
<button id="dirty-button" ng-click="addText(); myForm.myText.$setDirty()">Make Dirty</button>
<hr>
<form name="myForm">
<input name="myText" id="myTextInput" type="text" ng-model="myText" required>
</form>
<br/>
<span ng-show="myForm.myText.$dirty">it's dirty now</span>
A simple function:
$scope.addText = function() {
$scope.myText = "now I'm dirty";
}
$scope.$on('$viewContentLoaded'){
$scope.form.fieldName.$dirty = true;
}
When your view is loaded then angular calls viewContentLoaded event is called. After that you can set the field dirty. And also if you want to call some method ,that should be executed after the content is loaded than you should call that method inside this $scope.$on('$viewContentLoaded'){..}
This should do the job
angular.element(document.querySelector('form')).scope().formname.fieldname.$setDirty()

jQuery remove selected element, dynamically generated

I have a form and I can dynamically add more lines but if I try to remove a specific line it does not work, however the first line gets removed with no problem.
Here is the html:
<form class="order-form">
<div class="product-lines">
<!-- Product Line Section -->
<div class="product-line">
<img alt="remove" src="img/close.png" />
<input class="input-text" name="product-code" type="text" placeholder="Product Code" ></input>
<input class="input-text" name="product-quantity" type="text" placeholder="Quantity"></input>
<input class="input-text" name="product-discript" type="text" placeholder="Discription of Product"></input>
<label class="label-sign">£</label>
<input class="input-text" name="product-price" type="text" placeholder="RRP Price"></input>
<br>
</div>
</div>
<div id="product-btn">
<input name="btn-add-line" type="button" value="Add new line"></input>
<input name="btn-update" type="button" value="Update"></input>
<input name="btn-submit" type="submit" value="Submit Order"></input>
<label class="label-sign">£</label>
<input class="input-text" name="order-info" type="text" placeholder="Order total" ></input>
</div>
</form>
The jQuery code I have tried:
$(".btn-close").on("click", function(e){
$(e.currentTarget).parent().remove();
});
I've also Tried
$(e.currentTarget).parents("div.product-lines).next("div.product-line).remove();
Any help would be most appreciated, also a explanation would be very helpful for me to learn.
Try something like
$(".product-lines").on("click", ".btn-close", function(e){
$(e.currentTarget).parent().remove();
});
You cannot attach events to objects that are not currently on page (lines).
You have to attach click event on product-lines object and when it is clicked you delegate event to "closest" product-line object!
You will need to changed the jQuery slightly to allow for Event Delegation. This means all elements added in future will get the event attached to them too.
$(document).on("click", ".btn-close", function(e){
$(e.currentTarget).parent().remove();
});
$('body').on('click','button id/class',function(){
$(e.currentTarget).parent().remove();
});
but if u use this code it will remove <div class="product-line">...</div>
why you want to remove this div.
i dont get your question very well. Explain in details and step by step .

Trouble filling Multiple Textbox values from other Textboxes when Checkbox is Clicked

I DID search but couldn't find anything that helped me to figure out my particular issue. I've got textboxes for a customer address, and textboxes for a business address, and a checkbox to mark if the address should be the same. I need to get the Checkbox to fill the business address with the customer address onclick and unfill them on onclick. I've tried using a few different ways with jquery and straight javascript DOM manipulation, the most success I've had is in the following code, it only fills the biz_street textbox with the cust_street value though, and I don't understand why. Some help would be greatly appreciated, either in jquery or straight javascript, can't use php (sadly).
Here it is on jsfiddle (as suggested by rjmunro, good idea :) ): http://jsfiddle.net/yN73w/1/ not working at all
Here is the jquery:
$("#same_box").click(function () {
var v = $("#cust_street").val();
var x = $("#cust_city").val();
var y = $("#cust_state").val();
var z = $("#cust_zip").val();
$("#biz_street").val(v);
$("#biz_city").val(x);
$("#biz_state").val(y);
$("#biz_zip").val(z);
});
Or more simply:
$("#same_box").click(function () {
$("#biz_street").val($("#cust_street").val());
$("#biz_city").val($("#cust_city").val());
$("#biz_state").val($("#cust_state").val());
$("#biz_zip").val($("#cust_zip").val());
});
And the HTML:
<label id="cus_street_label">Street</label></br>
<input type="text" name="cust_street" id="cust_street" style="width:90%" /></br>
<div id="cus_city">
<label id="cus_city_label">City</label></br>
<input type="text" name="cust_city" id="cust_city" style="width:100%" /></br>
</div>
<div id="cus_state">
<label id="cus_state_label">State</label></br>
<input type="text" name="cust_state" id="cust_state" style="width:70%" /></br>
</div>
<div id="cus_zip">
<label id="cus_zip_label">Zip</label></br>
<input type="text" name="cust_zip" id="cust_zip" style="width:65%" /></br>
</div>
<input type="checkbox" name="same_box" id="same_box" >Address Same as Customer</input></br>
<label id="biz_street_label">Street</label></br>
<input type="text" name="biz_street" id="biz_street" style="width:90%" /></br>
<div id="biz_city">
<label id="biz_city_label">City</label></br>
<input type="text" name="biz_city_box" id="biz_city_box" style="width:100%" /></br>
</div>
<div id="biz_state">
<label id="biz_state_label">State</label></br>
<input type="text" name="biz_state_box" id="biz_state_box" style="width:70%" /></br>
</div>
<div id="biz_zip">
<label id="biz_zip_label">Zip</label></br>
<input type="text" name="biz_zip_box" id="biz_zip_box" style="width:80%" /></br>
</div>
Thank you very much for any help, and I apologize if I missed a topic like this in my searching.
(Also, unrelated, but why doesn't function formReset() {
document.getElementById("customer").reset();
} work in firefox? It only seems to work in chrome)
(you need to select jQuery in your JSFiddle, like http://jsfiddle.net/7HGNx/)
Your code is referring to biz_city but the element's id is biz_cty_box.
You probably don't want to attach to click, you probably want listen to the change event, as this will fire when the option is changed without the mouse. I would also check that the change has been ticking the box, not unticking the box.
$("#same_box").change(function (e) {
if ($(this).is(":checked")) {
.
.
.
}
}

Can I recalculate a form field without a reload?

When a field in my form gets focus, I'd like a javascript function to be called that
calculates a value for that field without my putting in a specific button to do that.
Is this possible without causing the form to reload?
I have thought about making the Amount field read-only, and some other ways of doing this, but I'm looking to see if changing the Quantity field could cause the Amount field to change either using onchange in the Quantity field or onfocus in the Amount field.
Purchase Tickets<br>
<script type="text/javascript" language="JavaScript1.2">
<script type="text/javascript" language="JavaScript1.2">
document.write(
'<form name="InvGenPayTickets" action="'+PostURL+'"
onsubmit="return validateForm();" method=GET>');
</script>
<input type=hidden name="TplURL" value="GenPayCCInfo.html">
<input type=hidden name="CancelURL" value="Ooopsie.html">
<input type=hidden name="SuccessURL" value="Joanie.html">
<input type='hidden' name='TransDesc' id='TransDesc'
value="$_POST['TransDesc']; ?>" />
<input type='text' name='Quantity' id='Quantity' /> <br />
Amount<br />
$<input type='text' name='Amount' id='Amount' />
<input type="submit" value="Next">
<br>
</form>
Edit:
Here is the function that won't update. It is called if I use
<input type='text' name='Quantity'
id='Quantity' onchange="return retTotalAmt();" />
but the Amount field does not update. I am not able to update using a calc button either.
<script type="text/javascript" language="JavaScript1.2">
function retTotalAmt()
{
alert("Got here.");
var total_amt
= (document.getElementById('Quantity').value * ticketCost)
+ DonationAmount;
document.getElementById('Amount').value = total_amt;
}
</script>
Per request in comments:
<input type='text' name='Quantity'
id='Quantity' onchange="return retTotalAmt();" />
Edit -- Show Problem
<script type="text/javascript" language="JavaScript1.2">
var ticketCost = 40.00;
function EnterPage()
{
var currentTotalAmount = DonationAmount + ticketCost;
//DonationAmount moved up to ticketCost's scope fixed problem.
var DonationAmount = <?php echo($_POST['DonationAmount']); ?>;
document.getElementById('DonationAmountField').value = DonationAmount.toFixed(2);
document.getElementById('Quantity').value=1;
document.getElementById('Amount').value = currentTotalAmount.toFixed(2);
return;
}
Without using jquery:
<input type='text' name='Amount' id='Amount' onfocus="amountOnFocus();" />
Javascript:
function amountOnFocus() {
amountField = document.getElementById('Amount');
//Do calculations
amountField.value = resultOfCalculations;
}
If you wanted, you could also put a change event listener on the Quantity input so it will calculate when the value of that textbox changes.
EDIT: This onchange event works for me:
Markup:
<input type="text" id="txtChangeMe" onchange="txtChangeMeOnChange();" />
Javascript:
<script type="text/javascript">
function txtChangeMeOnChange() {
alert('changed');
}
</script>
I'm not quite sure what additional information you need, as you seem to be aware of all the ingredients for making this happen: You know that you want to detect an event, you know that you need to call a function, so I'm hoping I haven't missed something about what you're asking. I'm going to assume that you just need to know how to tie all these parts together.
The simplest example might be:
<input type="text" id="Quantity" value="10" onchange="document.getElementById('Amount').value = parseInt(document.getElementById('Quantity').value,10) * 10.0;" />
$<input type="text" id="Amount" value="100" />
though it's worth noting that this does not follow best-practices, which would involve binding an event listener separately.
On the off-chance that you accidentally typed "button" when you meant "field", I will also mention that you can update any other element's innner HTML with the ''innerHTML'' attribute, eg:
<input type="text" id="Quantity" value="10" onchange="document.getElementById('Amount').innerHTML = parseInt(document.getElementById('Quantity').value,10) * 10.0;" />
$<span id="Amount">100</span>
Of course, you can define the actual logic elsewhere, and just use ''onchange="yourFunction();"'' instead of putting everything inline, as well.
I know you mentioned "onchange" and "onfocus", though personally I tend to prefer "onkeyup", so that values will change as the user is typing.
Apologies if I've completely missed the point in your question.
Sure. Use something like this which will fire when quantity change:
$("#Quantity").change(function(){
// perform your calculations here
};
This requires the jQuery framework.
function calcPrice()
{
....
}
<input type='text' name='Quantity' id='Quantity' onchange='calcPrice();'/>
<input type='text' name='Amount' id='Amount' onfocus='calcPrice();'/>
Do you have access to jQuery? If not then you would have to bind an change event to your "quantity" input element to listen for a change of its input. Then you would simply need to modify the contents of the "amount" input.
https://developer.mozilla.org/en-US/docs/DOM/element.addEventListener
var el = document.getElementById("Amount");
el.addEventListener("change", changeAmount);
function changeAmount(){
var quantity = document.getElementById("Quantity");
quantity.value = "SET YOUR VALUE";
}
Try this solution
Html
<div class="form-group row">
<label for="inputQty" class="col-sm-4 col-form-label">Quantity</label>
<div class="col-sm-8">
<input onkeyup="CalculateItem();" onkeydown="CalculateItem();" onchange="CalculateItem();" onfocus="CalculateItem();" value="1" type="number" step="1" min="1" max="9999999" class="form-control" id="inputQty" required>
</div>
</div>
<div class="form-group row">
<label for="inputPrice" class="col-sm-4 col-form-label">Price</label>
<div class="col-sm-8">
<input onkeyup="CalculateItem();" onkeydown="CalculateItem();" onchange="CalculateItem();" onfocus="CalculateItem();" type="number" step="0.1" min="1" max="9999999" class="form-control" id="inputPrice" required>
</div>
</div>
<div class="form-group row">
<label for="inputPriceNoVat" class="col-sm-4 col-form-label">Price (no VAT)</label>
<div class="col-sm-8">
<input readonly type="text" class="form-control" id="inputPriceNoVat">
</div>
</div>
JS
<script type="text/javascript">
function CalculateItem()
{
try {
let inputPriceNoVat = $('#inputPrice').val() * $('#inputQty').val();
$('#inputPriceNoVat').val(inputPriceNoVat);
} catch (e) {
$('#inputPriceNoVat').val(0);
}
}
</script>

Categories

Resources