using radio buttons in php jqGrid - javascript

I have a jqgrid using php. In one of the columns i want to use two radio buttons (Yes/No). I have used a custom formatter for this..
$(function () {
function myelem (value, options) {
var radio1 = document.createElement('input');
radio1.id = 'radY';
radio1.type = 'radio';
radio1.name = 'appr';
radio1.value = 'Yes';
var radio2 = document.createElement('input');
radio2.id = 'radN';
radio2.type = 'radio';
radio2.name = 'appr';
radio2.value = 'No';
var label1 = document.createElement('label');
label1.setAttribute('for', radio1.id);
label1.innerHTML = 'Yes';
var label2 = document.createElement('label');
label2.setAttribute('for', radio2.id);
label2.innerHTML = 'No';
var container = document.createElement('div');
container.appendChild(radio1);
container.appendChild(label1);
container.appendChild(radio2);
container.appendChild(label2);
return container;
}
function myvalue(elem, operation, value) {
if(operation === 'get') {
return $(elem).val();
}
else if(operation === 'set') {
$('input',elem).val(value);
}
}
$("#list").jqGrid({
url: "fetch.php?sqlselect=1",
datatype: "json",
mtype: "GET",
colNames: ["Role", "Region", "Approved"],
colModel: [
{ name: "role", width: 60,editable:true},
{ name: "region", width: 60,editable:true},
{ name: "approved", width:250, editable:true, edittype:"custom", editoptions: {custom_element: myelem, custom_value:myvalue}}
],
onSelectRow: function(id){
if(id && id!==lastSel){
jQuery('#list').restoreRow(lastSel);
lastSel=id;
}
jQuery('#list').jqGrid('editRow',id,
{
keys : true,
url : "edit.php"
} );
},
.............
Everything works fine when edited except the radio button column. I can see the radio buttons onClick. But once i press enter the radio button value is not passed to my edit page. That's understandable coz myval function is reading the div element and not a radio element. Since there are two radio buttons (with the same name, so at point only one can be checked Yes/No), and it's not a single entity like a text box, in order to 'return' a myelem i had to use a div. Is there a way I can do this where i can fetch the radio element value?

I have figured it out.. All I needed to do was this:
function myvalue(elem, operation, value) {
if(document.getElementById('radY').checked) {
return "Yes";
}
else {
return "No";
}
}

Related

how to keep all the desired input values while changing the inputs to buttons?

When the array is correct it should turn the input fields to btn btn-success buttons (works). Now comes the part I cannot seem to get past: They don't keep their value inserted into the input field. Example: You insert the word "hello" in an input field (and we assume the word "hello" is correct) and it then turns to a green button. However it does not keep it's value. How can I achieve this, but with multiple input fields?
The code looks like this:
}).on('blur', function() {
var cValue = $(this).val();
if(cValue === "") {
return;
}
if (cValue === syllable) {
correctSylls.push(cValue);
console.log(correctSylls);
}
if (exercise.syllables.length === correctSylls.length) {
$(this).closest('.syll-row').find('input.syl-input').replaceWith(getCorrectBtn());
S.addRight();
S.playRight();
}
I tried appending to the button cValue, but that didn't work (as expected).
The function that creates the success button:
function getCorrectBtn() {
var correctBtn = $('<button/>', {
'class': 'btn btn-success buttonCorrect',
'type': 'button',
'id': "button" + CBC++
});
return correctBtn;
}
Here is the complete loop (how the input fields are created aswell):
$.map(exercise.syllables, function (syllable, j) {
if (!syllable || !syllable.trim().length) {
// If it doesn't exist or is an empty string, return early without creating/appending elements
return;
}
var innerSylCol = $('<div/>', {
class: 'col-md-3 inputSyllables'
});
var sylInput = $('<input/>', {
'type': 'text',
'class': 'form-control syl-input',
'name': +c++,
'id': +idsyll++
}).on('blur', function() {
var cValue = $(this).val();
if(cValue === "") {
return;
}
if (cValue === syllable) {
correctSylls.push(cValue);
console.log(correctSylls);
}
if (exercise.syllables.length === correctSylls.length) {
$(this).closest('.syll-row').find('input.syl-input').replaceWith(getCorrectBtn());
S.addRight();
S.playRight();
}
$(this).closest('.syll-row').find('input.syl-input').replaceWith(getCorrectBtn(cValue));
function getCorrectBtn(value) {
var correctBtn = $('<button/>', {
'class': 'btn btn-success buttonCorrect',
'type': 'button',
'id': "button" + CBC++,
'value': value
});
return correctBtn;
}
This possibly should work.
Understand how replaceWith works. You aren't simply altering the existing input, you are replacing it. Since the value is data for the input, when you replace it, you are wiping out the data. So you must pass the data into the getCorrectBtn function and assign it to the new button.

How to pass values of selected checkboxes from multiple pages in Data Table

I have records in bootstrap data table which has pagination and each record will have a checkbox. Let say when I click some checkboxes in page 1 and some checkboxes in page 2, the form will only pass value of checkbox in page 2. How can I retrieve the checkbox values from page 1?Any help is much appreciated.
var checkboxes = $("input[type='checkbox']"),
btn = $("#btnCutoff");
//structure of table
var table = $('#table').DataTable({
"bLengthChange": false,
"pageLength": 5,
"bFilter": false
});
//disable button when no records are selected
btn.attr("disabled","disabled");
checkboxes.on('click', function(event) {
if($(this).prop('checked')){
btn.removeAttr('disabled');
} else {
btn.attr("disabled",!checkboxes.is(":checked"));
}
});
$("#table tbody").on("click",".clickable-row", function (event) {
if (event.target.type !== 'checkbox') {
$(':checkbox', this).trigger('click');
}
});
when clicks button, it will go to a javascript function
function doEnquiry(){
var f = document.frm;
f.method = "POST";
f.action = "test.jsp";
f.target = "_self";
f.submit();
}
and I want to assign the checkbox values to here
String curr[] = request.getParameterValues("chkTest");
Can anyone help me?
On every checkbox click if the checkbox is checked create a hidden field to store its value.You can rely on the hidden field values to capture all the checkbox values you want and can easily access them on the server side instead.
checkboxes.on('click', function(event) {
if($(this).prop('checked')){
btn.removeAttr('disabled');
$('form').append('<input type="hidden" name="fieldname" value="'+this.value+'" />');
} else {
btn.attr("disabled",!checkboxes.is(":checked"));
}
});
Jquery code
$(document).ready(function() {
$('#viewlist').DataTable();
$("#button").click(function() {
var chcklist = new Array();
var oTable = $('#viewlist').dataTable();
var rowcollection = oTable.$("#emp_name:checked", {"page": "all"});
rowcollection.each(function(index,elem) {
chcklist.push($(elem).val());
});
$.post(
"../accounts/updateSalaryHold.jsp",
{list: chcklist},
function (values) { }
);
});
});
jsp page Code
String[] arrayVal = request.getParameterValues("list[]");

Unable to select values from the select list

my select list is getting populated via a service call but I cannot select any of the values from the select list.
AJS.$("#select2-actor").auiSelect2(
{
placeholderOption: 'first',
formatResult: function(actor) {
return '<b>' + actor.text ;
},
data: function ()
{
var data = [];
AJS.$.ajax({
dataType: 'json',
type: 'GET',
url: AJS.params.baseURL+"/rest/leangearsrestresource/1.0/message/list/{actor}",
async: false
/*multiple: true*/
}).done(function(result) {
result = JSON.parse(result.value);
for (var actor in result.actors) {
data.push({
text : result.actors[actor]
});
//AJS.log(data)
}
});
return {
results: data
};
}
}
);
<div class="field-group">
<label class="label">Actor Select</label>
<input id="select2-actor" type="hidden" name="actor" style="width: 415px;" placeholder="Add an actor"/>
</div>
I am unable to figure out where I am going wrong.
Here is the JSFiddleLink
Here is the working fiddle: https://jsfiddle.net/64djszjf/14/
If you take a look at the source js file: https://aui-cdn.atlassian.com/aui-adg/5.8.13/js/aui-experimental.js, there are few lines that sets unselectable class:
populateResults: function(container, results, query) {
var populate, id=this.opts.id;
populate=function(results, container, depth) {
var i, l, result, selectable, disabled, compound, node, label, innerContainer, formatted;
results = opts.sortResults(results, container, query);
for (i = 0, l = results.length; i < l; i = i + 1) {
result=results[i];
disabled = (result.disabled === true);
selectable = (!disabled) && (id(result) !== undefined);
compound=result.children && result.children.length > 0;
node=$("<li></li>");
node.addClass("select2-results-dept-"+depth);
node.addClass("select2-result");
node.addClass(selectable ? "select2-result-selectable" : "select2-result-unselectable");
which indicates that this js file requires id attribute of the object passed in.
My fix was to simply add id field to your javascript:
for (var actor in result.actors) {
data.push({
text : result.actors[actor],
id: "1"
});
AJS.log(data)
}
This also indicates that you might want to change your REST service to return ids, along with the names of Actors.

jqgrid inline editing: dynamically set column editable properly of another column

When I change the value of a particular column during inline edit, I want to change the editable property value of another column of the same row dynamically. Below is a part of my code:
{ name: "admin", width:250, editable:<?php echo $owner; ?>, edittype:"custom", editoptions: {
custom_element: myelem,
custom_value:myvalue,
dataEvents: [{
type: 'change',
fn: function (e) {
var $this = $(e.target), $td, rowid;
var radSel = $(e.target).val(); //alert(radSel);
if(radSel == "No"){
if ($this.hasClass("FormElement")) {
$("#request").prop("editable", true);
} else {
//alert("you are here!!");
var row = $this.closest('tr.jqgrow');
var rowId = row.attr('id'); //alert(rowId);
$("#" + rowId + '_request').prop("editable", true);
}
}
}
}]
}},
{ name: "request", width: 100},
......
function myelem (value, options) {
var radio1 = document.createElement('input');
radio1.id = 'radY';
radio1.type = 'radio';
radio1.name = 'appr';
radio1.value = 'Yes';
if(value.match(/^Yes.*/)){ radio1.checked = true; }
var radio2 = document.createElement('input');
radio2.id = 'radN';
radio2.type = 'radio';
radio2.name = 'appr';
radio2.value = 'No';
if(value.match(/^No.*/)){ radio2.checked = true; }
var label1 = document.createElement('label');
label1.setAttribute('for', radio1.id);
label1.innerHTML = 'Yes';
var label2 = document.createElement('label');
label2.setAttribute('for', radio2.id);
label2.innerHTML = 'No';
var container = document.createElement('div');
container.appendChild(radio1);
container.appendChild(label1);
container.appendChild(radio2);
container.appendChild(label2);
return container;
}
function myvalue(elem, operation, value) {
if(document.getElementById('radY').checked) {return "Yes";}
else if(document.getElementById('radN').checked) {return "No";}
else {return ""; }
}
When i change the radio button to "No", it does enter into the if loop (under dataEvents) but the editable property on the 'request' column is not set to true dynamically. Any help much appreciated. thanks.
The editable property will be used by jqGrid before starting editing. If you want to prevent editing dynamically you have to set disable or readonly property/attribute on the corresponding existing editing field instead of setting editable property.
Moreover you seems to assign fix id attributes ('radN', 'radY') for custom editing field. It's dangerous because you can have id duplicates. Inline editing allows you to editing more as one row at the same time. In the case two custom editing elements with the same ids will be created and you will have problems. I recommend you additionally to set <input> inside of <label>. In the case you will don't need any id or for attributes. Try
<label><input type="radio" name="appr" checked="checked" value="Yes"/>Yes</label>
<label><input type="radio" name="appr" value="No"/>No</label>
One can check the radio button by clicking on the label.

change textbox value in client side and read it in server side

I have some textbox and I change the value of this textboxes in clientside (javascript) ,value was changed but when I read in server side after postback actually value not changed. my textbox isn't read only or disable.
notice that I use updatepanel and my postbacks is async.any idea to solve this issue?
update
I use this jquery to support placeholder in ie,but it cause value of my textboxes equal to placeholder value, and this conflict when my postback is async. for solving this problem I use below jquery code:
function EndRequestPostBackForUpdateControls() {
//*****************************For place holder support in ie******************************
if (runPlaceHolder != 0) {
//alert('end');
$('input, textarea').placeholder();
var $inputs = $('.placeholder');
$inputs.each(function () {
var $replacement;
var input = this;
var $input = $(input);
var id = this.id;
if (input.value == '') {
if (input.type == 'password') {
if (!$input.data('placeholder-textinput')) {
try {
$replacement = $input.clone().attr({ 'type': 'text' });
} catch (e) {
$replacement = $('<input>').attr($.extend(args(this), { 'type': 'text' }));
}
$replacement
.removeAttr('name')
.data({
'placeholder-password': $input,
'placeholder-id': id
})
.bind('focus.placeholder', clearPlaceholder);
$input
.data({
'placeholder-textinput': $replacement,
'placeholder-id': id
})
.before($replacement);
}
$input = $input.removeAttr('id').hide().prev().attr('id', id).show();
// Note: `$input[0] != input` now!
}
$input.addClass('placeholder');
$input[0].value = $input.attr('placeholder');
} else {
$input.removeClass('placeholder');
}
});
}}
function safeActiveElement() {
// Avoid IE9 `document.activeElement` of death
// https://github.com/mathiasbynens/jquery-placeholder/pull/99
try {
return document.activeElement;
} catch (err) { }}
function BeginRequestPostBackForUpdateControls() {
//*****************************For place holder support in ie******************************
if (runPlaceHolder != 0) {
// Clear the placeholder values so they don't get submitted
var $inputs = $('.placeholder').each(function () {
var input = this;
var $input = $(input);
if (input.value == $input.attr('placeholder') && $input.hasClass('placeholder')) {
if ($input.data('placeholder-password')) {
$input = $input.hide().next().show().attr('id', $input.removeAttr('id').data('placeholder-id'));
// If `clearPlaceholder` was called from `$.valHooks.input.set`
if (event === true) {
return $input[0].value = value;
}
$input.focus();
} else {
alert($(this)[0].value);
$(this)[0].value = '';
alert($(this)[0].value);
$input.removeClass('placeholder');
input == safeActiveElement() && input.select();
}
}
});
}}
$(document).ready(function () {
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_beginRequest(BeginRequestPostBackForUpdateControls);
prm.add_endRequest(EndRequestPostBackForUpdateControls);
});
I use this code to clear my textbox value before sending to server in add_beginRequest,and set value in add_endRequest (for placeholder in ie).
can anyone help solve this problem? thank you.
You changed the value of TextBox with javascript and the respective ViewState is not updated. You can use hidden field to store the value in javascript and get it in code behind.
Html
<input type="hidden" id="hdn" runat="server" />
JavaScript
document.getElementById("hdn").value = "your value";
Code behind
string hdnValue = hdn.Value;
Use hidden field to store the value, and retrieve it on the server side.

Categories