How to maintain checkbox value through pagination? - html

I have a list of products which are shown with pagination and I can filter the display of the products using check boxes. The problem is it can only displays the value from check box at first page, and if i go to the next page, i will lose the check box checked's value. Please help me how to solve this. I don't know where should I put input hidden and how to write Java Script. Here's my code:
<input id="checkbox_brand" type="checkbox" name="checkbox_brand[<? echo $data_brand[brand_name]; ?>]" value="<? echo $data_brand[brand_name]; ?>"/>
if (isset($_POST["checkbox_brand"])){
foreach($_POST["checkbox_brand"] as $status_a) {
$status_sql[] = '\''.$status_a.'\'';
}
$status = implode(',',$status_sql);
session_start();
$_SESSION["selected"]=$status;
}
if (session_is_registered("selected")){
-->my query
}

Each time you press a check box you'll have to use dictionary array in JavaScript
For example:
if I use the example page you gave, then when pressing a check box inside "Categories"
you'll have to put a value inside correct variable.
// Initialize Objects
var userChoice = {};
userChoice.Catagories = {};
userChoice.Brands = {};
userChoice.ScreenSize = {};
.
.
.
// Pressing check box will trigger the bellow
userChoice.Categories["LG"] = 0;
userChoice.Categories["Sharp"] = 1;
userChoice.Categories["Sony"] = 1;
userChoice.Brands["LcdTV"] = 1;
userChoice.Brands["LedTV"] = 0;
Each checkbox press will also trigger the following JavaScript
document.getElementById("userChoiceHiddenField").value = JSON.sringify("userChoice");
When submitting the page or going to the next page the hidden value will contain the JSON string, so you can parse it as JSON again.
Server Side: (.NET)
string userChoiceHiddenField = request["userChoiceHiddenField"].ToString();
and then take the value you got and place it back in the hidden field and the JavaScript value as follows:
userChoice = JSON.parse(document.getElementById("userChoiceHiddenField").value);
Hope that answers your question.

Related

Add class to bootstrap textbox - yii2

I have a form in yii2. In that I have a input field like below.
<input type="text" class="form-control" id="productsales-<?= $i ?>-value">
It's inside a dynamic form andno coming from any model.It's just to hold some calculated value. And the idea is to calculate the values fileed by users in this field to another textbox like below -
<?= $form->field($model, 'amount')->textInput(['maxlength' => true, 'class' => 'sum']) ?>
I already have the javascript code to calculate the total amount like below -
<?php
/* start getting the total amount */
$script = <<<EOD
var getSum = function() {
var items = $(".item");
var sum = 0;
items.each(function (index, elem) {
var priceValue = $(elem).find(".sumPart").val();
//Check if priceValue is numeric or something like that
sum = (parseFloat(sum) + parseFloat(priceValue)).toFixed(2);
});
//Assign the sum value to the field
$(".sum").val(sum);
};
//Bind new elements to support the function too
$(".container-items").on("change", ".sumPart", function() {
getSum();
});
EOD;
$this->registerJs($script);
/*end getting the total amount */
?>
Please note that I have a class sum in the second textbox which comes from a model. My question is that how can I add a class(sumPart) like this(sum) in the first textbox which is not coming from a model.
Update after discussion with Insane Skull
I have a dynamic form like below
I want to calculate sum of all the entries in Value and pass it to amount.
The code of Value is -
<input type="text" class="form-control sumPart" id="productsales-<?= $i ?>-value">
The code of Amount is -
<?= $form->field($model, 'amount')->textInput(['maxlength' => true, 'class' => 'sum']) ?>
The javascript I've tried is already given above.
The problem with this code is the calculated "value" is not passing to amount textbox.
Update: A little issue
Modify JS :
$this->registerJs('
function getSum() {
var sum = 0;
var items = $(".item");
items.each(function (index, elem) {
var priceValue = $(elem).find(".sumPart").val();
sum = parseFloat(sum) + parseFloat(priceValue);
});
if(isNaN(sum) || sum.length == 0) {
sum = 0;
}
$(".sum").val(sum);
}
$(".container-items").on("change", function() {
getSum();
});
jQuery(".dynamicform_wrapper").on("afterDelete", function(e) {
getSum();
});
');
I am little unsure about the problem you are facing. If you want to add a class to a input field, you can easily do so in the class attribute of the input tag. And the class attribute does support multiple values, so you can write something like this:
<input type="text" class="form-control sumPart" id="productsales-<?= $i ?>-value">
**UPDATE -- based on comment by OP **
#Tanmay, I understand that you may not be getting the desired output. However, it should not really matter if we are rendering the fields using $form->field() or plain HTML. If the fields have the proper classes assigned, then the JS code posted by Kostas in your referenced link should work - irrespective of how the class name was added to the input field.
Can you please confirm (by using Inspect Element) if the sumPart class is actually assigned to the relevant fields once the page loads? Maybe some JS is overwriting the class attribute again?
If the classes are assigned properly, please check if there are any other JS errors in console which may prevent the sum calculation JS from working properly.

Is there a way I can check to see if the "go to page based on answer" is checked in Google Forms

When using .setChoices() It looks for an array of created choices. If it is a multiple choice question it can be formatted either createChoice(value) or createChoice(value, navigationType).
When looking at a choice you put in something like: var cPage = chkItem.getChoices()[j].getGotoPage();
This will produce either the page object or a Null value.
The problem is when a question is set to "go to page based on answer" and they have not set a page for every entry, and left the default to continue it also reads it (in my case cPage), as null. This means if I want to go through each choice to capture it, modify it, then push it back out to the question, it my ending Array that I push out consists of both Null and Objects, which produces an error.
My workaround for questions without pages is for the script to forcibly change the question to handle page navigation but set everyone to CONTINUE.
I would like to find a way to check if the question has "go to page based on answer" checked and if not then be able to create choices using just the value.
Figured it out: I need to check the first choice if it has a PageNavigationType(). If it does then the box is checked. If null then it is not checked. I have not written the code to fully test this but the theory should work. (I was checking against just the goToPage type which is why it didn't work before. )
var choicecount = chkItem.getChoices().length-1;
var hasNavType = chkItem.getChoices()[0].getPageNavigationType(); //if null
for (var j = 0; j <= choicecount; ++j) {
var cValue = chkItem.getChoices()[j].getValue();
var cPage = chkItem.getChoices()[j].getGotoPage();
var cNav = chkItem.getChoices()[j].getPageNavigationType();
// Logger.log(j+" "+cPage);
if (cValue != reValues[0]){
if (hasNavType == null){
newChoices.push(chkItem.createChoice(cValue));
} else {
if (cPage == null){
newChoices.push(chkItem.createChoice(cValue,cNav));
} else {
newChoices.push(chkItem.createChoice(cValue,cPage));
}
}
}
}

Setting input value with html code crashes the input

I am trying to make a web to change the data base. The problem is that some attributes from the DB are in html format, and when I try to set the input's value to the current DB attribute, it crashes.
The code that I use is the following:
$('#projectlist').DataTable( {
"createdRow": function ( row, data, index ) {
var ele = $('td', row).eq(1);
var id_input = $('td', row).eq(0);
id_input = id_input[0].innerHTML;
ele[0].innerHTML = '<input id="'+id_input+'" value="'+ele[0].innerHTML+'" style="width:100%; height: 25px;">';
},
data: data
} );
This just sets the second element from the table to be an input with the value equal to the DB.
But when the DB has html code like this one
text \" moretext
the input finishes at the \ and following text is shown as regular text instead of input.
here's an image of the problem. As you can see the top input is how it should be showing and the bottom input has the text that doesn't stay inside in the input box, it justs contiunes like text.
like k-nut said, doing it with jquery solves the problem. If someone is interested, changing the code to this solved the problem:
var ele = $('td', row).eq(1);
var id_input = $('td', row).eq(0);
var content=ele[0].innerHTML;
id_input = id_input[0].innerHTML;
ele[0].innerHTML = '<input id="'+id_input+'" style="width:100%; height: 25px;">';
$( "#"+id_input ).val(content);

Create a data-persistent select option

I am dynamically populating a select tag with cities in the US.
Depending on which state the user selects, a city select tag gets dynamically populated with cities from that state. The options for the city are created via a js function which does its job just fine. This function is called on the 'onchange' event within the state select html tag.
As it currently works, the entirety of these fields are within a form. Every field is required to be data-persistent, ie the data you type into these fields must be "filled out" after the form has been submitted. All fields currently on the page, except the dynamically filled city field are persistent and work as intended. This is accomplished by creating CF variables in a format like so:
<cfparam name="form.highschoolstate" default="" />
<cfparam name="form.highschoolcity" default="" />
<cfparam name="form.highschool" default="" />
and at each input, a format similar to this:
<select name="highschoolstate" id="highschoolstate" required="required" onchange="stateswitch('highschoolstate')" value="#form.highschoolstate#">
However, there is one kink in the form, the cities that populate my "High school city" field are not data-persistent. I have, for each state, a list of all of the cities in a format like so:
<option value=\"akiachak\">Akiachak</option>
But when (please see the below picture for result) I try to make the data-persistent, using innerHTML (by replacing the contents of the select tag) I get this code that is undesireable.
<option value=\"akiachak\" <cfif form.highschoolcity EQ \"akiachak\">selected=\"selected\"</cfif>>Akiachak</option>
Is there an option available to put this conditional CF statement within my dynamically generated html such that I can have persistent data throughout my entire form?
Function that dynamically changes the select tag:
//Dynamically changes the drop down list when selecting a city/state pair
function stateswitch(id)
{
var myId = id; //ID of the html element we are changing
var stateFlag = false; //This flag turns true when we have selected a state
var highschoolStateFlag = false; //This flag turns true when we have selected a highschool state
var indexInSelect; //Index selected in the select tag
var selectTag1; //Select tag # 1
var selectTag2; //Select tag # 2 that becomes available after select tag # 1 is selected
if(myId == "state")
{
indexInSelect = document.getElementById("state").selectedIndex;
selectTag1 = document.getElementById("state").options;
selectTag2 = document.getElementById("city");
state = selectTag1[indexInSelect].value;
if(selectTag1[0] == "") //If we haven't selected an option before
{
document.getElementById("state").remove(0); //remove the default/null case
stateFlag = true;
}
if(stateFlag)
indexInSelect = indexInSelect - 1; //accounts for offset of default case in indecees to select from
}
else
{
indexInSelect = document.getElementById("highschoolstate").selectedIndex;
selectTag1 = document.getElementById("highschoolstate").options;
selectTag2 = document.getElementById("highschoolcity");
document.getElementById("highschool").disabled = false;
document.getElementById("highschool").placeholder = "Required";
highschoolstate = selectTag1[indexInSelect].value;
if(selectTag1[0] == "") //If we haven't selected an option before
{
document.getElementById("highschoolstate").remove(0); //remove the default/null case
highschoolStateFlag = true;
}
if(highschoolStateFlag)
indexInSelect = indexInSelect - 1; //accounts for offset of default case in indecees to select from
}
selectTag2.disabled = false; //Disable the second select box (because we know at this point we have selected an option for the first one)
switch(selectTag1[indexInSelect].value)
{
case "alabama":
selectTag2.innerHTML="<option value=\"abbeville\" <cfif form.highschoolcity EQ \"abbeville\">selected=\"selected\"</cfif>>Abbeville</option><option value=\"abernant\" <cfif form.highschoolcity EQ \"abernant\">selected=\"selected\"</cfif>>Abernant</option>";
break;
case "ANOTHER_STATE":
selectTag2.innerHTML="etc...<option value=\"...</option>"
break;
//..
}
}
EDIT - SOLUTION:
What I was trying to do was not possible, so I decided on another approach
From the information that you provided I think the problem is with the \ character in the ColdFusion code. You need that to escape the quotation marks for the JavaScript code but not for the ColdFusion code. Try removing those characters from the <cfif> statements in the JavaScript code.
Instead of this:
<cfif form.highschoolcity EQ \"abbeville\">selected=\"selected\"</cfif>
Try this:
<cfif form.highschoolcity EQ "abbeville">selected=\"selected\"</cfif>
You do not need to escape the quotation marks in the ColdFusion code because the ColdFusion server will process that code before it is output to the user's browser.

How do I substitute unseen name-value pairs (from radio buttons) in my CGI script?

Cross from PerlMonks, see bottom.
UPDATE: Perhaps the best way to do this is through HTML or JavaScript(I know nothing of these)?
Objective
After the whole code is run and an output is given, I'd like to provide a hyperlink to re-run the code, with the same search word, but different radio buttons pressed.
Here is a portion of my CGI script, related to the user input:
my $search_key = param('query');
my $c_verb = param('verb_only');
my $c_enabling = param('enabling');
my $c_subject = param('subject');
my $c_object = param('object');
my $c_prep = param('prep');
my $c_adj = param('adjective');
my $c_modnoun = param('modnoun');
my $category_id;
if ($c_verb eq 'on')
{
if ($c_enabling eq 'on')
{$category_id = 'xcomp';}
elsif ($c_subject eq 'on')
{$category_id = 'subj';}
elsif ($c_object eq 'on')
{$category_id = 'obj';}
elsif ($c_prep eq 'on')
{$category_id = 'prep';}
I don't have access to the HTML, but from viewing the source code, all the $c_... have the form:
<input type="checkbox" name="verb_only" onClick="ch...
The "unseen" in the title is referring to no appended name/tag value pairs, so I don't know what to change, Where can I find this information?
I was thinking of changing $c_enabling to $c_subject and another link to a case where it was as if $c_prep was chosen from the user. Is there a way to substitute the name-value pairs of that single param? (So user inputs options, runs, instead of going back to input different ones, just click hyperlink, because some options stay the same)
The URL of the form is like: http://concept.whatever.com/test.html and the output is at the URL: http://concept.whatever.com/cgi-bin/search2011.cgi
My attempt
See posted answer
UPDATE: I've tried `url(-query) but nothing was appended to the end...
Thanks for any advice. Let me know if this is not clear.
Original: http://www.perlmonks.org/?node_id=910616.... Particularly applying this advice: http://www.perlmonks.org/?node_id=910630
If the method of the HTML is changed to GET instead of POST:
<form name="search_option" action="http://localhost/cgi-bin/mytestsearch2011.cgi" method="get">
Then the tags can be viewed (I had to copy the source code and do this on my localhost to check them)
I was able to find out what tags and values to put, b/c get method. So here is the working code:
if ($category_id eq "xcomp") {
my $subjurl = "http://localhost/cgi-bin/mytestsearch2011.cgi?query=$search_key&verb_only=on&subject=on&exclude0=&exclude1=&exclude2=&exclude3=";
print qq(Subject\n)." ";
my $objurl = "http://localhost/cgi-bin/mytestsearch2011.cgi?query=$search_key&verb_only=on&object=on&exclude0=&exclude1=&exclude2=&exclude3=";
print qq(Object\n)." ";
my $prepurl = "http://localhost/cgi-bin/mytestsearch2011.cgi?query=$search_key&verb_only=on&prep=on&exclude0=&exclude1=&exclude2=&exclude3=";
print qq(Preposition\n)."<br><br>";
}
elsif ($category_id eq "subj") { ##List urls other than what is currently output:
my $enablingurl = "http://localhost/cgi-bin/mytestsearch2011.cgi?query=$search_key&verb_only=on&enabling=on&exclude0=&exclude1=&exclude2=&exclude3=";
print qq(Enabling Function\n)." ";
...
I don't understand all the exclude tags, but that's okay...
UPDATE: This works with POST as well, I just needed to know all the tags that came after the URL. Thanks!