How can I write and read bool values into/from cookies? - html

I want to save the state of checkboxes in an html form on submit to cookies, and then enable/disable other parts of my site based on those cookie values.
I've started out with code like this:
HTML:
<form method="POST">
<fieldset>
<legend>(Not really) Opt In or Out</legend>
<input type="checkbox" id="selectTwitter" name="selectTwitter" >I'm Twitterpated!</input><br />
. . .
Razor:
#{
var twitterSelected = false;
. . .
if (IsPost)
{
twitterSelected = Request["selectTwitter"].AsBool();
Response.Cookies["TwitterSelected"].Value = twitterSelected.ToString(); // Doesn't seem to accept saving boolean vals - saved as "false" or "true"?
Response.Cookies["TwitterSelected"].Expires = DateTime.Now.AddYears(1);
. . .
...but am stuck on how to check or uncheck the checkboxes based on possibly existing cookie vals:
if (Request.Cookies["selectTwitter"] != null)
{
// what now?
}

Cookies are strings. You'll need to convert the cookie value to the type you want. The boolean values are being saved as true or false because that's the string representation of a boolean.
var selectTwitterCookie = Request.Cookies["selectTwitter"];
bool selectTwitter = false;
if(selectTwitterCookie != null)
{
bool.TryParse(selectTwitterCookie, out selectTwitter);
}
Alternatively, you could use Convert.ToBoolean(selectTwitterCookie).

Related

change a variable value using *ngIf in angular 7

I am trying to add some validation using [pattern] in an angular 7 application. I want to disable a button using a variable this.isSubmitDisabled if the pattern has errors ( phoneNumber.errors?.pattern ).
I know that this can be achieved using Reactive form but unfortunately, I cannot use forms. Is there a way to set the variable value to 'true' if phoneNumber.errors?.pattern is true?.
Here is my code:
<input
type="text"
class="form-control"
(ngModelChange)="dialInDetailsChange($event)"
name="dialInDetails"
[disabled]="false"
id="dialInDetails"
pattern="^\d+(?:[,.]\d+)?$"
required
[(ngModel)]="agendaMeeting.dialInDetails"
ngModel #dialInDetails="ngModel" />
You can also check it using .match() in your .ts file. On model change just check whether the entered value matches your regex. If matches then set inputDisabled to false otherwise set inputDisabled to true.
let inputDisabled:boolean = false;
dialInDetailsChange(event:any){
if(agendaMeeting.dialInDetails.match("^\d+(?:[,.]\d+)?$") === null){
inputDisabled = true;
}
else{
inputDisabled = false;
}
}
Edit after recent comment
WORKING DEMO : LINK
myInput='';
result='';
changeHandler(){
if(this.myInput.match('^[\\s]+[a-zA-Z]*') === null){
this.result = "correct input";
}
else{
this.result = "there are spaces at the begining."
}
}
i think you can't assign values using expression in your template, check the documentations
You can't use JavaScript expressions that have or promote side effects, including:
Assignments (=, +=, -=, ...)
Operators such as new, typeof, instanceof, etc.
Chaining expressions with ; or ,
The increment and decrement operators ++ and --
Some of the ES2015+ operators
try this :
<input
type="text"
class="form-control"
(ngModelChange)="updateState(phone)"
name="dialInDetails"
[disabled]="false"
id="dialInDetails"
pattern="^\d+(?:[,.]\d+)?$"
required
[(ngModel)]="agendaMeeting.dialInDetails"
#phone="ngModel" />
<button type="button" [disabled]="isDisabled">Submit</button>
updateState(input){
this.isDisabled = input.errors && input.errors.pattern ? true : false ;
}

How to filter or custom filter array of objects based on matching values from another object

I implemented an advance search with 15 input fields in AngularJS.
In the page load itself the result set is return from database in JSON format and i need to do the filter in client side only.
The input criteria's equivalent column is available in the result set and i need to check in its respective column only.
I am converting each column by JSON.stringify() and check with the search params like the below :
$scope.filteredData = $scope.actualData.filter(function(item) {
return JSON.stringify(item.FirstName).toLowerCase().indexOf(lowerFirstName) != -1 &&
JSON.stringify(item.LastName).toLowerCase().indexOf(lowerLastName) != -1 &&
JSON.stringify(item.EmailAddress).toLowerCase().indexOf(lowerEmailAddress) != -1 &&
JSON.stringify(item.Address1).toLowerCase().indexOf(lowerAddress1) != -1 &&
JSON.stringify(item.Address2).toLowerCase().indexOf(lowerAddress2) != -1;
...... etc // upto 15 fields
});
Since i have the 15 input fields and the actual result set contains a minimum of 50,000 records.
So converting each record's each column by JSON.stringify() and check with search params will surely cause the performance issue.
Is there any other way to achieve the filtering in client side with other approach.
I posted a sample code in Plunker with 5 input fields only : http://plnkr.co/edit/nUWZEbGvz7HG6gb91YZP
sylwester's answer is the normal way you'd filter things. Your code looks like you want to filter down to only the object that matches every input field. You code attempts to find an object where every property matches the searchParams object. At that point, I don't see what benefit there is to finding that object, because the user already created the object again! Nonetheless, here's a proper version of your code:
Live demo here.
<div ng-repeat="data in actualData | filter:searchData()">
$scope.searchData = function() {
return function(item) {
return Object.keys(item).every(function(key) {
// skip the $$hashKey property Angular adds to objects
if (key === '$$hashKey') { return true; }
var searchKey = key.charAt(0).toLowerCase()+key.slice(1);
return item[key].toLowerCase() === $scope.searchParams[searchKey].toLowerCase();
});
};
};
You really need to limit the data coming from the server for the browser's sake and for the server's sake. It's easy to implement a LIMIT, OFFSET system. It sounds like, overall, you just need to be able to query the server for a certain record.
From your comments, it seems you definitely want Angular's built in filter filter:searchParams, and just capitalize your searchParams models to match your data. For fun, I'll include more options for finer tuning.
This one almost mimics filter:searchParams. You can change > 1 to adjust when the partial matching kicks in, or have it return true only when both items are strictly equal === to disable partial matching. The difference here is that all items are hidden until matched, whereas filter:searchParams will show all items and then remove what doesn't match.
Live demo here.
$scope.searchData = function() {
return function(item) {
return Object.keys(item).some(function(key) {
if (key === '$$hashKey') { return false; }
var searchKey = key.charAt(0).toLowerCase()+key.slice(1);
var currentVal = $scope.searchParams[searchKey].toLowerCase();
var match = item[key].toLowerCase().match(currentVal);
return currentVal.length > 1 && match;
});
};
};
Lastly, to perfectly mimic filter:searchParams, you'd just put in a check to NOT filter the items until there is user input and the input is long enough to start the partial match.
Live demo here.
$scope.searchData = function() {
var partialMatchLength = 2;
return function(item) {
var shouldFilter = Object.keys($scope.searchParams).some(function(key) {
return $scope.searchParams[key] && $scope.searchParams[key].length >= partialMatchLength;
});
if (!shouldFilter) { return true; }
return Object.keys(item).some(function(key) {
if (key === '$$hashKey') { return false; }
var searchKey = key.charAt(0).toLowerCase()+key.slice(1);
var currentVal = $scope.searchParams[searchKey].toLowerCase();
var match = item[key].toLowerCase().match(currentVal);
return currentVal.length >= partialMatchLength && match;
});
};
};
First of all you ng-repeter with 50.000 records more likely is going to kill your browser, so you should thing about pagination.
Secondly you can easy filter your data using angular filter please see that demo
http://plnkr.co/edit/R8b8G4xCMSQmX1144UJG?p=preview
<div ng-controller="ListCtrl">
<br />
First Name:
<input type="text" id="txtFirstname" ng-model="searchParams.FirstName">
<br/>Last Name:
<input type="text" id="txtLastname" ng-model="searchParams.LastName">
<br/>Email Address:
<input type="text" id="txtEmailAddress" ng-model="searchParams.EmailAddress">
<br/>Address 1:
<input type="text" id="txtAddress1" ng-model="searchParams.Address1">
<br/>Address 2:
<input type="text" id="txtAddress2" ng-model="searchParams.Address2">
<br/>
<button class="btn btn-primary" ng-click="searchData()">Search</button>
<br />
<hr />
<b>Filtered Data(s):</b>
<div ng-repeat="data in actualData | filter:searchParams ">
<span ng-bind="data.FirstName"></span>
<span ng-bind="data.LastName"></span> |
Address : {{data.Address1}}
</div>
<hr />
</div>

How to maintain checkbox value through pagination?

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.

Dynamically created checkboxes using ajax from sql result set

I am looking to use ajax to dynamically create checkboxes each time you change your selection from a <select> tag, see the below screenshot for a section of the form that is relevant:
NOTE: The checkboxes under "Queues" should be dynamic.
At the moment, when you change the value for Team it grabs the team name (in this case "Test"), then using ajax (POST) it returns the Manager name for that team.
What I want it to do is look up another table that has a list of the "queues" associated with each team; I am going to add an "onchange" attribute in the tags for the "Manager Name" field.
Below is the code I'm currently using to accomplish the Team => Manager Name dynamic filling:
<script>
window.onload = function() {
getManager($("#team").val());
}
function getManager(team) {
$.ajax({
type: "POST",
url: "getManager.php",
data: {team:team}
}).done(function( manager ) {
$("#manager_name").val(manager);
});
}
</script>
And here is the getManager.php file that it uses:
<?php
require("../../database/db.php");
$mysqli = new db("nab_reporting");
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
$team=$mysqli->real_escape_string($_POST['team']);
$result = $mysqli->query("SELECT manager_name FROM team WHERE teamname = '".$team."'");
$row = $result->fetch_assoc();
echo $row['manager_name'];
mysqli_close($mysqli);
?>
Keeping in mind that the above works; I now need a way to use the onchange attribute of the Manager Name field that will use ajax (similar to above), passing another php page the value that is currently in the field (in this case Kane Charles) and will return a result set (array or JSON maybe?) containing a list of all queues in the database that match up with that Team name.
Below is the html code for each of the different bits:
TEAM
<select name="team" id="team" required="required" onchange="getManager(this.value)">
<?php
include(__DIR__ . "/../../database/db.php");
$db = new db("nab_reporting");
$result = $db->query("SELECT teamname FROM team");
while ($row = $result->fetch_assoc()) {
echo "
<option value=\"" . $row['teamname'] . "\">" . $row['teamname'] . "</option>
";
}
$db->close();
?>
</select>
MANAGER NAME
<input type="text" name="manager_name" id="manager_name" required="required" onchange="getQueues(this.value)">
QUEUES
<label>
Queues
</label>
<div id="queue_options">
<!-- queues dynamically created here -->
</div>
I need the contents of queue-options to be erased and reset to only the queues associated with the current team; I haven't done a great deal with ajax, hence why I'm posting on here.
This revision should match what you are asking about
PHP
// make an array to hold the queues
$data = Array();
// Fetch the rows of all the queues
$res = $mysqli->query("SELECT * FROM the_queue_table WHERE manager='" . $_GET["manager"] . "'");
// loop through all the rows and push the queues into the data array
while(($row = mysql_fetch_object($res)) !== false)
{
array_push($data, $row->queue);
}
// return the data array as a json object
echo json_encode($data);
JavaScript
// get the page and send the manager name to filter with
$.get("file.php?manager=" + managerName, function(page)
{
// parse the json into an object
var data = $.parseJSON(page);
// remove existing checkboxes
$("#queue_options").children().remove();
// add checkboxes to the div
for (var item in data){
$("#queue_options").append("<input type=\"checkbox\" value=\"" + item + "\" />" + item + "<br />");
}
});

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.