How to back to begin process jQuery - javascript

I have a modal form and an input field with checkbox type. I want to create an update form, so I should request data from php and passing to html. So I have two conditions, if parameter = 0 attribute checked="checked", else attribute checked become unchecked. So I use jQuery, this is my code:
<input class="form-check-input" type="checkbox" value="Ya" name="agenda_pimpinan" id="tampilkan_agenda_pimpinan" checked="checked"/>
<script type="text/javascript">
var x = event.tampilkan_agenda_pimpinan;
console.log(x);
if(x != 0) {
$('#tampilkan_agenda_pimpinan').removeAttr("checked");
}
else {
$('#tampilkan_agenda_pimpinan').attr("checked");
}
</script>
Assume I have two data that I want to update, we assume the names data1 and data2. Data1 have parameter = 0 and Data2 have parameter = 1. If I click data1, the modal form will come in. The attribute checked has success become still checked. Next, I click data2, the attribute checked has success become unchecked. But if I back click data1, the attribute checked become unchecked. I don't know how to write code so that the attribute will back to begin.
How to fix it?

$(function () {
var x = event.tampilkan_agenda_pimpinan;
//$('#tampilkan_agenda_pimpinan').attr("checked");
if (x != 0) {
$('#tampilkan_agenda_pimpinan').removeAttr("checked");
} else {
$('#tampilkan_agenda_pimpinan').attr("checked");
}
});

Related

How can i process value get from checkbox by JS then do something with it in Java action?

I have a checkbox like this in JSP
<input type="checkbox" id="checkBox" name="checkBox"/>
In JS file I wrote a function to set data for a variable when checkbox be clicked
$("checkBox").change(function(){
var checkBox= 0;
if(this.checked) {
checkBox= 1;
} else {
checkBox= 0;
}
})
Then in Java action class I want to do something when checkbox be clicked
if(bean.getCheckBox == 1) {//do something}
But it's not working. Please help me fix this one ! thanks
The var checkBox is a client-side JavaScript local variable and its value will only ever be visible inside the change event listener; your action class which (I'm assuming) is a server side component will not have access to this value.
Your action class should instead check for the value of the checkBox request parameter which comes from the value attribute.
<input type="checkbox" id="checkBox" name="checkBox" value="1" />
Then in your action class you'll have something like:
if ("1".equals(request.getParameter("checkBox"))) {
...
}
Or, you can also simply do a null-check and not check for any specific value.
if (request.getParameter("checkBox") != null) {
...
}
If you're using some framework bean, you'll use something like below depending on the bean's checkBox variable's data type.
if ("1".equals(bean.getCheckBox())) { // String
...
}
// or
if (bean.getCheckBox() != null) { // String or Integer
...
}
// or
if (bean.getCheckBox() == 1) { // int primitive
...
}
The value to check for still comes from the value attribute above.

Dynamically check javascript value after database update

I am developing a dynamically generated and self updating form in ASP.NET MVC using javavascript, Jquery, JSON/Ajax calls.
Here is how I set up my view code from the controller. I loop through all available controls from the controller:
<ul>
#using (Html.BeginForm("Index", "WebMan", FormMethod.Post)) {
foreach (var row in Model.controls)
{
<li>
<label>#row.Name</label>
#if (row.ControlType == "STRING" || row.ControlType == COMMENT")
{
<input type="text" name="#row.Name" id="#row.NameID" value="#row.Value" data-original-value="#row.Value" class="form-control data-field" style="width: 300px"/>
}
else if (row.ControlType == "DDL")
{
<select name="#row.Name" id="#row.NameID" class="form-control data-field" value="#row.Value" data-original-value="#row.Value" style="width: 300px">
#foreach (var o in row.Options)
{
<option value="#o.Value">#o.Text</option>
}
</select>
}
</li>
}
<button type="submit">Update</button>
}
</ul>
(notice that I set the value to the value from the database and I also set the “data-original-value” to the value from the database as well)
I am using the “data-original-value” to check to see if the value has changed later.
I also set up a javascript timer that executes every 5 seconds. This timer is meant to “update” the page. (code for timer below)
var interval = setInterval(function () { Update(); }, 10000);
When the timer executes, we loop through each control in the “data-field” class. This allows me to check each dynamically generated control.
Basically, If a user has edited a control, I DO NOT want to update that control, I want to ignore it. I only want to update that specific control if a user has not changed the value. When a user changes the value, the current value != orig value (Data-original-value), so we set the field to yellow and ignore the database update code.
function Update() {
UpdateControls();
}
function UpdateControls() {
$(".data-field").each(function () {
var nameAttr = $(this).attr('name');
var id = $(this).attr('id');
var val = document.getElementById(id).value;
var origVal = $(this).data("original-value");
if (origVal == val) {
//user did not change control, update from database
var url = "/WebMan/UpdateControlsFromDB/";
$.ajax({
url: url,
data: { name: nameAttr },
cache: false,
type: "POST",
success: function (data) {
if (data != null) {
document.getElementById(id).setAttribute("data-original-value", data);
document.getElementById(id).value = data;
}
else {
alert(data);
}
},
error: function (response) {
alert("Issue updating the page controls from database");
}
});
}
else {
document.getElementById(id).style.backgroundColor = "yellow";
//user changed control, do not update control and change color
}
});
}
If no change, this ajax method in my controller is called:
[HttpPost]
public ActionResult UpdateControlsFromDB(string name)
{
var curValue= db.Setup.Where(x => x.Name == name).Select(x =>Value).FirstOrDefault();
return Json(curValue);
}
The code works correctly if a user modifies the field. It senses that the user modifies the code, and changes the field yellow.
The part that does not work correctly, is if the database updates the field. When the database first updates the field, it looks great. We set the “data-original-field” value to the value as well, to tell our code that is should not turn yellow and the user has not modified it.
But after another update, “value” and “original-value” do not match. The code document.getElementById(id).value somehow gets the OLD version of the control. It does not get the current value. So then on next loop, the values don’t match and we stop updating from DB and the control turns yellow.
My issue is that my code senses that the control value changed (database update) and turns it yellow, when I only want to turn the control yellow when a USER has changed the value in the control.
I only want to change the control and prevent updating from DB when the control has been modified by the user.
Thank you for any help.

Javascript Checkbox Ticked on Load Error

I have a .cshtml page that I'm going to set up with several checkboxes.
The checkboxes should be checked/unchecked depending on the values of several variables passed into the view using the TempData.
I've set up the code as follows:
<script>
#if (TempData["enabled"] == "True") {
var eCheckBox = document.getElementById(eCheck);
eCheckBox.checked = true;
}
</script>
<h2>Update #TempData["fullName"]</h2>
<input type="checkbox" name="enabledCheckbox" value="Enabled" id="eCheck"/>Enabled<br/>
But the line
eCheckBox.checked = true;
produces the error 'identifier expected;checked is a keyword'. Is there something obvious I'm missing? Making a checkbox ticked on load seems like it should be simple to do.
EDIT: I tried to correct the code as follows:
<input type="checkbox" name="enabledCheckbox" value="Enabled" id="eCheck" onload="checkTrue()"/>Enabled<br/>
<script type="text/javascript">
function checkTrue() {
alert("Here!");
if (TempData["enabled"] == "True") {
document.querySelector('[name=enabledCheckbox]').checked = true;
}
}
</script>
It doesn't look as though the code is hitting the function at all, as no alert fires.
You miss to retrieve your HTML element correctly through JS. Just use this:
document.querySelector('[name=enabledCheckbox]').checked = true;

My checkbox doesn't work with loop for to display data

I did the checkbox work good, this is my one:
$(document).ready(function(){
$('input[type="checkbox"]').click(function(){
if($(this).prop("checked") == true){
document.getElementById("srt").value = document.getElementById("Ultra").value;
}
else if($(this).prop("checked") == false){
document.getElementById("srt").value = "";
}
});
});
At my display data part, I have the loop for to show all the record. I want after I click the checkbox the value I get from document.getElementById("Ultra").value and display on document.getElementById("srt").value. It work good at 1 record only, the rest I check didn't work. I think the problem is I display it on <input type="text" id="srt"> and the textbox I put in loop with loop for to display database. Any help?
This one is php part:
for ( $v = 0 ; $v < mysql_num_rows($result) ; $v++ )
{
$row = mysql_fetch_assoc($result);
?>
<td><input type="checkbox"/></td>
<?php
echo'<td>'.$row['aaa'].'</td>';
echo'<td>'.$row['bbb'].'</td>';
echo'<td>'.$row['ccc'].'</td>';
echo'<td><input type="text" id="srt"></td>';//////this one to display value i get
echo'<td>'.$row['dddr'].'</td>';
}
The value only display on 1 row only.
One thing I see is you have <input type="text" id="srt"> in each loop. This means your ids are not unique and this could cause problems in the document.getElementById("srt").value = document.getElementById("Ultra").value; call.
Try make ids unique (this means giving a different id for every textbox, maybe something like srt_'.$v.' and also retrieving the correct textbox id in the jquery function)
PS: can you please show also the "Ultra" input in your php code?
Edit: to get the correct textbox you could set an id to your checkbox too and use it to get the correct id of the textbox.
In your page:
echo'<td><input type="checkbox" id='.$v.'/></td>';
and
echo'<td><input type="text" id="srt'.$v.'"></td>';
And in your function
if($(this).prop("checked") == true){
document.getElementById("srt"+this.id).value = document.getElementById("Ultra").value;
}
I did not test it so there could be something to adjust, but the idea is there.
try this..
$(document).ready(function(){
var values = $('input.high_name:checked').map(function () {
return this.value;
}).get();
alert(values);
});
and your checkbox add class name,
<input type="checkbox" value="" name="high[]" class="high_name">

Javascript replace method not functioning in checkbox if/else toggle

I have a bit of Javascript I'm playing with, which is called by a number of checkboxes and will ideally perform an action (adding and removing &attributeValue=attribID to the URL cumulatively) upon the checkbox being checked/unchecked.
Here's the Javascript:
var filterBaseURL = <?="\"".$url."\""?>; /*This is just copying a php variable that contains the base URL defined earlier - all of this works fine*/
var filterFullURL = filterBaseURL;
function filterToggle(attribID)
{
var elementII = document.getElementById(attribID);
if(elementII.checked){
filterFullURL = filterFullURL+"&attributeValue="+attribID;
}
else {
filterFullURL.replace("&attributeValue="+attribID, "");
alert(filterFullURL);
}
}
So what I'm doing here is attempting to on check of a checkbox add that checkbox's attributeValue to the URL, and on uncheck of a checkbox, remove that checkbox's attributeValue from the URL. I am using the filterFullURL = filterFullURL+"..." because there are multiple checkboxes and I want all their attributeValues to cumulatively be added to the URL.
All of this is working fine - the only thing that isn't working fine is the else statement action -
filterFullURL.replace("&attributeValue="+attribID, "");
Here are some example checkboxes:
<input type="checkbox" onclick="filterToggle('price_range_0_20')" name="Price_Range" value="Below_$20" id="price_range_0_20" /> Below $20
<input type="checkbox" onclick="filterToggle('price_range_20_40')" name="Price_Range" value="$20_-_$40" id="price_range_20_40" /> $20 - $40
<input type="checkbox" onclick="filterToggle('price_range_40_70')" name="Price_Range" value="$40_-_$70" id="price_range_40_70" /> $40 - $70
So to recap - I can add the attributeValues of all the checkboxes together, but I can't delete any of them. Any help here? Thanks!
Do you not need to save the output of filterFullURL.replace like filterFullURL = filterFullURL.replace("&attributeValue="+attribID, "")?
There was also an alert missing from the if statement - not sure if that's intentional, but this should operate well for you:
var filterBaseURL = <?="\"".$url."\""?>; /*This is just copying a php variable that contains the base URL defined earlier - all of this works fine*/
var filterFullURL = filterBaseURL;
function filterToggle(attribID)
{
var elementII = document.getElementById(attribID);
if(elementII.checked){
filterFullURL = filterFullURL+"&attributeValue="+attribID;
alert(filterFullURL);
}
else {
filterFullURL = filterFullURL.replace("&attributeValue="+attribID, "");
alert(filterFullURL);
}
}

Categories

Resources