Checking checkboxes on webform via URL query string - javascript

I'm working on a registration form with several classes from which one can choose more than one (checkboxes). There is also a corresponding fee that is popped into a textbox for each class.
One also must select one membership category (radio buttons).
Each checkbox item has a unique ID and value. They are all named "courses[]". When the form is submitted, the values are sent to the registration desk via a php script that writes to a database and sends email (and all the courses' titles are under "Courses").
Here's the issue:
I want visitors of the website to be able to click on a link next to the class they want. The link is a URL query string that pre-fills the regform with the default membership category and also checks the checkbox next to the class. But so far it's only working for the radiobutton option of membership and not for the checkbox classes. I need to modify or replace the code to accommodate these checkboxes, but I need help.
The URL query string I am using looks like this (not a real URL):
https://domain.edu/summer.php?membership=Current&courses=ClassTitle_12345
Here's the pertinent script from the form page [loads after DOM]:
function getUrlParameters() {
var urlQuery = location.search;
urlQuery = urlQuery.replace('?', '');
if (urlQuery.indexOf('&') == -1) {
checkPreselectedMembership(urlQuery);
checkPreselectedMembership(urlQuery);
} else {
var params = urlQuery.split('&');
for (var i = 0; i < params.length; i++) {
checkPreselectedMembership(params[i]);
}
}
total();
}
function checkPreselectedMembership(param) {
var split = param.split('=');
if (split[0] == "membership") {
if (split[0].match(/^[0-9a-zA-Z_]{1,20}$/)) { // only allow numbers, letters, and the underscore
document.getElementById(split[1]).checked = true;
}
}
}
And here a snippet of the HTML:
<input name="courses[]" type="checkbox" id="class01" onClick="classFees();total();" value="ClassTitle1_12345" title="Check to select course">
Class Title 1</td>
$<input name="class01_fee" size="10" type="text" readonly title="class fee">
<input name="courses[]" type="checkbox" id="class02" onClick="classFees();total();" value="ClassTitle2_34568" title="Check to select course">
Class Title 2</td>
$<input name="class02_fee" size="10" type="text" readonly title="class fee">
I hope that I have been clear with my questions. Thank you.

Related

Assign value from endpoint to checkbox

I am trying to assign values I get from an endpoint to a checkbox
Here is the object
{sendOtpEmail: true}
I had to do some searching inside the endpoint response to differentiate whether an email value comes back or a cell phone value comes back
Here is my code
TS
otpCellValue: any;
otpEmailValue: any;
getOTPChannel() {
this._loader.start();
this._subscriptions.push(this._corpService.getOTPChannel().subscribe((resp) => {
//get endpoint object
console.log(resp);
//get endpoint object parameter name
let keyNames = Object.keys(resp);
console.log(keyNames[0]);
//check for email keyword
if(keyNames[0].includes('Email')) {
console.log(resp.sendOtpEmail);
//get value
if(resp.sendOtpEmail == true) {
//email value is true so the otpEmailValue checkbox should be checked however it is not
this.otpEmailValue = 1;
this.otpCellValue = 0;
} else {
this.otpEmailValue = 0;
this.otpCellValue = 0;
}
}
this._loader.stop();
}, (error) => {
this._loader.stop();
this._errorService.openErrorPopup('Failed to get OPT channel.');
}));
}
HTML
<input type="radio" name="1" id="1" class="with-gap" [(ngModel)]="otpCellValue" [(value)]="otpCellValue">
<input type="radio" name="2" id="2" class="with-gap" [(ngModel)]="otpEmailValue" [(value)]="otpEmailValue">
I added comments to say what I am doing in the code above
So now I am stuck with why the email checkbox is not checked. Any ideas?
Those are not checkboxes but radio buttons. Assuming that you do want the radio buttons (which in your case it looks like it, because it would be one or the other), there are a few things that needs to be done.
Rather than having 2 properties to indicate which option is selected, you could have 1 property for that purpose.
So
this.otpEmailValue = 1;
this.otpCellValue = 0;
Becomes
this.contact = 'email'; // This line is now equivalent to the ones above
In the template, the radio button inputs, need to have the same name for them to behave as 1 input instead of 2, because after all, we only want 1 option selected. The ngModel directive now points to the value we want to bind, in our case, contact. And lastly, the value should be static. When the value of the property bound with ngModel matches the value of one of the radio buttons, it will select it.
So, after all those changes we get the following.
<input type="radio"
name="contact-option"
id="1"
class="with-gap"
[(ngModel)]="contact"
value="cell"> Cell
<input type="radio"
name="contact-option"
id="2"
class="with-gap"
[(ngModel)]="contact"
value="email"> Email
Demo

How to create a clickable list with multiple values in an element?

I am trying to create a list of names an user could chose from to select a object with multiple hidden values. I work with a PHP backend.
The code I wrote works but I think it is probably not the right way to approach the problem and could be written alot better, but I can't seem to find a better way.
Right now I print a <div> for every object which are clients in my case. Within the div I have four checkboxes that are hidden, which I check and uncheck on the background with a javascript function. The values of those checkboxes is what I need in javascript for an API call after the user choses the client.
I select and deselect the with a javascript function.
foreach($clients as $client) {
echo '<div class="'.$client->name.'-'.$client->id.' client-style" name="'.$client->name.'">
<input type="checkbox" class="'.$client->id.'" name="client_id" value="'.$client->id.'">
<input type="checkbox" class="'.$client->id.'" name="client_fb" value="'.$client->facebook.'">
<input type="checkbox" class="'.$client->id.'" name="client_insta" value="'.$client->instagram.'">
<input type="checkbox" " class="'.$client->id.'" name="client_wb" value="'.$client->website.'"></div>';
}
For every element I create an on click event handler
for (var i = 0; i < clientList.length; i++) {
const {name, id} = clientList[i];
$(`.${name}-${id}`).on('click', function() {
selectClientFromList({name, id});
});
}
I am trying to get a list of clickable "names". When a "name" is clicked, you want to get the "name" but also "id", "facebook", "instagram", "website".
Might be useful to use the <select> tag with multiple values like this but I don't want a dropdown. I need a scrollable list, because I also have use searchbar for this list.
With a lot of clients the html would grow fast. How do I clean my php code and keep the information about a client that the user selected?
Thanks in advance!
A good approach can be to use a hidden input. Give your div a class and then
foreach($clients as $client) {
echo '
<div class="'. $client->name.'-'.$client->id.' client-style" name="'.$client->name.'">
<input type="hidden" class="aclass '.$client->id.'" name="client_id" value="'.$client->id.'">
<input type="hidden" class="aclass '.$client->id.'" name="client_fb" value="'.$client->facebook.'">
<input type="hidden" class="aclass '.$client->id.'" name="client_insta" value="'.$client->instagram.'">
<input type="hidden" class="aclass '.$client->id.'" name="client_wb" value="'.$client->website.'"></div>';
}
And then instead of creating a click handler everytime. One works too.
$(`.aclass`).on('click', function() {
let type = $(this).attr('name'); // client_id or client_fb
let client_id = $(this).attr('class').replace("aclass",""); // $client->id's value is here
let value = $(this).val(); // credentials
});

How to display a textbox if "others" option from checkbox group is checked

I want to display a text box using JavaScript when the "Other" option is checked from a group of checkboxes. I'm using razor pages with asp.net core 2.2
I'm using the following script but it is not working.
function onSelectChange() {
var sel = document.getElementById('QuestionOptionId');
var strUser = sel.options[sel.selectedIndex].text;
if (strUser.startsWith('Other'))
document.getElementById('textBox').disabled = false;
else
document.getElementById('textBox').disabled = true;
}
</script>
Fruits.cshtml ( razor page view file)
#foreach (var option in Model.QuestionOptions)
{
<input type="checkbox" asp-for="QuestionOptionId" id ="QuestionOptionId" value ="#option.Value" onclick="onSelectChange()" /> #option.Text<br />
}
QuestionOptions is a selectList:
Value=1 Text= Apple,
Value=2 Text= Kiwi,
Value=3 Text =Other
whenever the user checks the checkbox for "Other", it should display a textbox.
What am I doing wrong here? I have read so many other answers but not able to figure out this one.
Update-1
I don't know why the post is not showing the textbox control...
I'm pasting it here again, it is outside the foreach loop. I have removed the angle brackets as I think it is mixing with formatting.
input type="text" id="textBox" name="response" disabled="disabled"
Full disclosure: I have never used Razor pages or asp.net
I'm having a hard time following how your javascript is detecting whether the other option is checked. It seems like your Fruits.cshtml is going to generate three separate inputs with the same "QuestionOptionId" id.
Also, your Fruits.cshtml snipped doesn't include the code for the textbox you'd like to enable, though I'm assuming you have a textbox with id "textBox" in the compiled HTML that you'd like to enable.
I would change your script out for this:
function onSelectChange(element) {
if (element === element.parentNode.querySelector(".other")) {
console.dir(element);
if (element.checked) {
document.getElementById("textBox").disabled = false;
} else {
document.getElementById("textBox").disabled = true;
}
}
}
You'll need to add the "other" class to your applicable "Other" input checkbox. You'll also need to change your Fruits.cshtml snippet so that the "onclick" function also passes the applicable element into the script.
#foreach (var option in Model.QuestionOptions)
{
<input type="checkbox" asp-for="QuestionOptionId" id ="QuestionOptionId" value ="#option.Value" onclick="onSelectChange(this)" /> #option.Text<br />
}
Here's a working example of the compiled code: https://codepen.io/bourn404/pen/yWVLdx
Try the following modification in the view and the javascript:
Add the label outside the input
#foreach (var option in Model.QuestionOptions)
{
<Lable>
<input type="checkbox" asp-for="QuestionOptionId" id="QuestionOptionId" value="#option.Value" /> #option.Text
</Lable>
<br />
}
<div>
<input type="text" id="textbox" disabled="disabled" />
</div>
Use $(this).parent().text().trim() to get the text
$('input:checkbox').on('click', function () {
if ($(this).parent().text().trim() === "Other") {
$('#textbox').removeAttr("disabled");
}
});
Update
If you want to hide the text box and hide the textbox when you uncheck the "other option , firstly you could change the disabled attribute to hidden ,and then determine if the text box contains hidden attribute in js like below :
<input type="text" id="textbox" hidden />
if ($(this).parent().text().trim() === "Other")
{
if ($('#textbox').is(':hidden')) {
$('#textbox').removeAttr("hidden");
}
else {
$('#textbox').attr("hidden", "hidden");
}
}

How to copy checkbox form fields from 1 form to another?

I have an HTML form built with PHP that basically shows a list of records, this list of records has a FORM because it has a Checkbox filed next to each record which allows me to mass do actions on a set of records.
My issue is I recently added in a comments section under each record and that comment section allows for a quick comment post, so it has it's own FORM for each records comment section, this of course broke my checkbox form as the comment forms close </form>
At the bottom of the list of records is a drop down form field which list actions I can do with the Selected checkboxes records. This is the part that no longer works as it cannot have access to the checkboxes records list anymore as that is now part of a different <FORM>
So my thought on a quick solution, using JavaScript, if I can somehow copy hte checkbox form fields array to my new form at the bottom of that page to do mass record updates.
My checkbox fields next to each record look like this now...
<input id="cb-select-1" type="checkbox" name="record_update[]" value="' . $dbresult->id . '">
So using JavaScript is it possible to copy the contents of record_update[] to another new form field in a different Form on the page?
Here is a better example in very basic form to show what I need to accomplish....
<form name="Form-A" id="form-a">
<input id="cb-select-1" type="checkbox" name="record_update[]" value="355">
<input id="cb-select-1" type="checkbox" name="record_update[]" value="455">
<input id="cb-select-1" type="checkbox" name="record_update[]" value="555">
...lots more Database records with a checkbox to select the item for a mass record change
</form>
<form name="Form-B" id="form-b">
<!-- This hidden field should have an array of all the ID's from form-a that have CHECKED checkboxes ONLY -->
<input type="hidden" name="record_update_ids">
<input type="submit" name="" id="doaction2" class="button" value="Update Records">
</form>
UPDATED code that mass selects and de-selects my checkboxes on the page now...
<script type="text/javascript">
function checkAll(bx) {
var cbs = document.getElementsByTagName("input");
for(var i=0; i < cbs.length; i++) {
if(cbs[i].type == "checkbox") {
cbs[i].checked = bx.checked;
}
}
}
</script>
when you check a check box, adds an hidden input to the second form:
$("input[name='record_update[]']").click(function(){
var chkId = $(this).attr('id');
var chkVal = $(this).val();
if ($(this).is(':checked'))
$('<input>').attr({
type: 'hidden',
id: 'input_'+chkId,
name: 'input_'+chkId,
value: chkVal
}).appendTo('#secondForm');
else
//if isn't checked removes it
$('#input_'+chkId).remove();
});
when you click in the 'Check All' button, adds all to the text area:
$("#chkAl").click(function(){
$("input[name='record_update[]']").click(function(){
//skips the already checked
if (!($(this).is(':checked')))
$(this).click();
});
});
You can use http://api.jquery.com/clone/
http://jsfiddle.net/MA3x4/1/
In document ready do the following
$('#form-a').find('input:checkbox[name="record_update[]"]').each(function () {
$(this).clone().appendTo('#form-b');
});

Adding checkbox values with different input names

I have the following code which adds together checkboxes when they are selected and produces a total at the bottom of the page. This function uses the following code:
<script type="text/javascript">
function checkTotal() {
document.listForm.total.value = '';
var sum = 68.50;
for (i=0;i<document.listForm.choice.length;i++) {
if (document.listForm.choice[i].checked) {
sum = sum + parseFloat(document.listForm.choice[i].value);
}
}
document.listForm.total.value = sum.toFixed(2);
}
</script>
These checkboxes are within a form, and I need the form to send through to an email account. At the moment because all the checkboxes share the same input name 'choice' the PHP will only send the last checked box value.
I need to change the checkboxes input name code to name the different checkboxes 'choice1' 'choice2' 'choice3'. What would I have to change in the javascript to in order for the function to calculate all the checkboxes names 'choice1' 'choice2' 'choice3' etc rather than just adding together all checkboxes named'choice'? I have little Javascript and PHP knowledge so any help would be grateful. Thanks.
Rather than make the checkbox names unique, it would be better to append "[]" to their name. This will cause PHP to convert the values into an array, rather than just keep the last value.
So you would want a name of choice[] rather than choice.
You can also find some sample code in this answer.
The code below works ok (a self contained web page). The problem is how to get the array (group) of checkboxes when they're called different names. If you use jquery you could give them all the same class, then get hold of them by that class, but if you're using bare javascript then you can get the elements by Tag name ("input" in the case of the checkbox), and check each one has a name attribute that starts with "choice", inoring those that don't start with "choice", like buttons (also an input) or maybe other checkboxes with different names. It's a bit inefficient if the page is huge, unless you group the checkboxes some way.
To group them, you cold put them in a tag like
`<div id="checkboxes"> (checkboxes go here) </div>`
then use
`var cb = document.getElementById("checkboxes");`
`var arrInputs =cb.getElementsByTagName("input");`
for the line to get the arrInputs array. This would just get input type elements from within the Div. Hwever I dind't want to assume the page layout allows your checkboxes to be put in one div
Hope this helps
Doug
<script type="text/javascript">
function checkTotal() {
document.forms.listForm.total.value = '';
var sum = 68.50;
var frm=document.forms.listForm; // wasnt sure what your original listForm element was so I've put this form into a variable, frm
frm.total.value = '';
var arrInputs =document.getElementsByTagName("input"); // get all Input type elements on the form
for (i=0; i < arrInputs .length;i++) {
if (arrInputs[i].name.substr(0,6) == "choice") { // if the name starts with "choice"
if (arrInputs[i].checked) {
sum = sum + parseFloat(arrInputs[i].value);
}
}
}
frm.total.value = sum.toFixed(2);
}
</script>
</head>
<body>
<form name="listForm">
<a href='javascript:checkTotal()'>check</a><br>
<input type=checkbox name="choice1" value="1"><br>
<input type=checkbox name="choice2" value="2"><br>
<input type=checkbox name="choice3" value="3"><br>
<input type=checkbox name="choice4" value="4"><br>
<input type=checkbox name="choice5" value="5"><br>
<input type=checkbox name="choice6" value="6"><br>
<br>
<input type=text name=total value=""><br>
</form>
</body>
</html>

Categories