Append parameters to a URL based on checkboxes - php

So I have a list of 8 checkboxes in a form. These checkboxes are supposed to control a link that will load in a frame. However I have no idea where to start...
Checkbox1(appendThis1) - checked
Checkbox2(appendThis2)
Checkbox3(appendThis3) - checked
Checkbox4(appendThis4)
Checkbox5(appendThis5) - checked
Checkbox6(appendThis6)
Checkbox7(appendThis7)
Checkbox8(appendThis8)
So based on this I would have a base URL such as http://www.google.com and since checkbox1,3, and 5 are check the appendThis1, appendThis2, appendThis3 would be added to the end of the url but none of the other checkboxes would append anything to the URL. Each checkbox would add or remove its specific parameter to the URL.
Also whenever a checkbox is check it will reload the URL.

The way I would go at this, is as follows
make sure in your html form, all the checboxes have the same name with empty square braces at the end, this way you will get an array back in php. As the value you should set the string you want to append to your html. something like this:
<input type="checkbox" value="q=something" name="myCheckboxes[]" /> option 1
<input type="checkbox" value="lang=en" name="myCheckboxes[]" /> option 2
...
in your php code, just implode te array you get back trough the post, and append it to your html. (see more info here http://www.html-form-guide.com/php-form/php-form-checkbox.html). The pseudo-code would look like this:
$url = 'http://www.google.com?';
$checkboxes = $_POST['myCheckboxes'];
$url .= implode('&', $checkboxes);
for the automatic submit when a checkbox is checked, you will need some client side script. My choice would be jQuery and it would look like this:
$('#myForm input[type="checkbox"]').change(function() {
$('#myForm').submit();
};
Note that none of the code is tested, but it should work fine, or at least point you in the right direction. Corrections are welcome of course!

Example with raw Javascript. You can work out loading your iframe with the resulting URL.
jsFiddle
<script language='javascript'>
arr_sel = new Array();
function constructURL(cv)
{
if (arr_sel.length==0)
{
arr_sel.push(cv);
} else {
if (inArray(cv, arr_sel))
{
key = getKey(cv, arr_sel);
arr_sel.splice(key,1);
} else {
arr_sel.push(cv);
}
}
makeURL(arr_sel);
}
function inArray(val, arr)
{
var length = arr.length;
for(var i = 0; i < length; i++) {
if(arr[i] == val) return true;
}
return false;
}
function getKey(val, arr)
{
for (var i = 0; i < arr.length; i++)
{
if (arr[i]==val)
return i
}
}
function makeURL(arr_sel)
{
opts = new String;
arr_opts = new Array();
for (var i = 0; i < arr_sel.length; i++)
{
arr_opts.push(arr_sel[i]);
}
url = 'http://google.com?' + arr_opts.join('&');
document.getElementById('myurl').innerHTML = url;
}
</script>
<input type=checkbox name=whatever value='opt1=foo' onClick="constructURL(this.value)"> foo <br>
<input type=checkbox name=whatever value='opt2=bar' onClick="constructURL(this.value)"> bar <br>
<div id='myurl'>http://google.com?</div>

Related

How to remove an input value before submitting it in Wordpress with the Ultimate member plugin

I want to know how to remove an input value before submitting a profile form in Wordpress with Ultimate Member plugin. I've been stuck with this for a whole week.
The thing is that I have conditional fields in the profile form that if the user does not select, they still save their values ​​when the form is submitted. The plugin does not remove the values ​​from the hidden fields conditionally, which is a problem if you want to send these fields elsewhere with REST API.
I couldn't do it with PHP so I added a script inside the principal function to try and clear the values. This work when user refresh the form, but not when user submit the form with the hook um_after_user_updated
function remove_before_send () {
?>
<script>
var elements = document.querySelectorAll('.um-is-conditional');
for (var i = 0; i < elements.length; i++) {
elements[i].childNodes[1].childNodes[0].value = "";
}
</script>
<?php
}
add_action('um_profile_content_main', 'remove_before_send');
EDIT:
Thanks to the comment of #JB_DELR. You really gave me all the clues.
This is my final code (im not proud, because i wanted to use php, but this is the best i could do)
function remove_before_send () {
?>
<script>
var boton = document.querySelector("div.um-left.um-half > input");
boton.addEventListener("click", function(){
var elements = document.querySelectorAll('.um-is-conditional');
for (var i = 0; i < elements.length; i++) {
if (elements[i].style.display == "none") {
elements[i].childNodes[1].childNodes[0].value = "";
}
}
});
</script>
<?php
}
add_filter( 'um_profile_content_main', 'remove_before_send');
Your js script need to handle the form submit event, prevent default submiting, remove unnecessary fields an submit the form itself.
Something like this:
<script>
var form = document.querySelector(<select the form>);
form.onsubmit = function(e) {
e.preventDefault(); // don't submit the form right now;
var elements = document.querySelectorAll('.um-is-conditional');
for (var i = 0; i < elements.length; i++) {
elements[i].childNodes[1].childNodes[0].value = "";
}
// to remove element, this remove the input field, so field is no more in the request
// elements[i].childNodes[1].removeChild(elements[i].childNodes[1].childNodes[0]);
}
form.submit();
</script>

Javascript compare string in an array

function getPublicLink() {
var div = document.getElementById('links'); // anchor tag
var url;
for(var x in div){
url += div[x].href;
}
}
This is for getting the list. My Problem is that I want to compare it with the json results below. If there is a matched. I will alter the anchor tag to remove the href attribute or make the text Connected ( Now it is "Invited"). The Linkedin connection code is:
function displayConnections(connections) {
var members = connections.values;
var publicUrl;
for(var member in members) {
publicUrl += members[member].publicProfileUrl;
}
}
My problem is they are in a big string. What i want is to compare them one by one. I'm out of ideas since I'm just a JS beginner. Thanks for your input!
I've found the answer.
for(var i in publicUrl) {
for(var j in url) {
if(url[j] === publicUrl[i]) {
alert("Found " + url[j]);
}
}
}

I'd like to detect the value chosen from a drop down, and then pass that to the page url and reload

I have some javascript sorting my ul, alphabetically a-z or z-a. It works fine on page one, but if there is more than one page it ignores the list on page 2 etc.
So, instead of using javascript to sort the li's, I want to pass the selection back to the page's query and reload
here's my script, most of which is redundant now.
var select = document.getElementById('organise');
$('#organise').change(function() {
if(select.value === 'A') {
$('.recipeTable li').sortElements(function(a,b){
var aText = $.text([a]);
var bText = $.text([b]);
return aText.toLowerCase() > bText.toLowerCase() ? 1 : -1;
});
} else {
$('.recipeTable li').sortElements(function(a,b){
var aText = $.text([a]);
var bText = $.text([b]);
return aText.toLowerCase() > bText.toLowerCase() ? -1 : 1;
});
}
});
So I want to detect the selected dropdown value (either A or Z) and pass that into the url and reload. I'm stuck ;-?
Rich :)
I am not sure this is the best way to approach the problem, and maybe you should elaborate what doesn't work with your pagination. In any case, you can achieve what you need to do by doing something like this (explaination in the code comments):
var queryString = {};
// Get the previous query string with a little help from PHP
// this shouldn't be a problem since you are already using PHP
// for your project.
queryString = <?php json_encode( $_GET ); ?>;
$('#organise').change( function() {
// Set the sort property of the object to the value of the select.
queryString.sort = $(this).val();
// jQuery will help you serialise the JSON object back to
// a perfectly valid query string (you may want to escape
// characters)
newQueryString = $.param( queryString );
// Append the new query string
window.location = newQueryString;
});
This function will properly check if you already have any query string and preserve that; also, if the user changes the select multiple times, it will not add up several query strings.
you can change the url and pass the param with
document.location.href = document.location.href + "?arg=" + document.getElementById("organise").value;
You can use localstorage for this if you don't want to show in url
For example:
function Ascending()
{
$('.recipeTable li').sortElements(function(a,b){
var aText = $.text([a]);
var bText = $.text([b]);
return aText.toLowerCase() > bText.toLowerCase() ? 1 : -1;
});
}
function Descending()
{
$('.recipeTable li').sortElements(function(a,b){
var aText = $.text([a]);
var bText = $.text([b]);
return aText.toLowerCase() > bText.toLowerCase() ? -1 : 1;
});
}
if(localStorage.order=='A')
{
return Ascending();
}
else
{
return Descending();
}
var select=document.getElementById('organise');
$('#organise').change(function() {
if(select.value === 'A') {
localStorage.order=='A';
return Ascending();
} else {
localStorage.order=='Z';
return Descending();
}
});
Refer more for localStorage on http://www.w3schools.com/html/html5_webstorage.asp

Javascript - Onclick event happening during and only during page load

I'm still fairly new to javascript and I'm not finding where I'm making my mistake. The basic set up I'm working with is a set of radio buttons along with a set of check boxes. Depending on the radio button picked only a specific set of check boxes should be available the rest should be disabled/grayed out. Which check boxes are allowed for a given radio button are passed in through a php array. In my code the exclusive choices refer to the radio buttons while the extended choices refer to check boxes. My javascript and php for this functionality is as follows:
window.onload = function(){
<?php
for($i = 0; $i < count($students_information); $i++){
foreach($exclusive_extended_array as $exclusive => $extended){
echo "$('".$i."_exclusive_".$exclusive."').onclick = allow(".$i.",".json_encode($extended).");";
}
}
?>
}
function allow(i, extended){
$('[id^="'+i+'Extended"]').disabled = true;
for (var j = 0; j < extended.length; j++) {
alert(extended[j]);
$(i+"Extended"+extended[j]).disabled = false;
}
}
On the loaded page it appears as:
<script type="text/javascript">
window.onload = function(){
$('0_exclusive_2176').onclick = allow(0,[1975]);
$('0_exclusive_911').onclick = allow(0,[]);
$('0_exclusive_795').onclick = allow(0,[1973,1975]);
}
function allow(i, extended){
$('[id^="'+i+'Extended"]').disabled = true;
for (var j = 0; j < extended.length; j++) {
alert(extended[j]);
$(i+"Extended"+extended[j]).disabled = false;
}
}
</script>
Unfortunately, what the code ends up doing is running the script when the page loads rather than when one of the radio buttons is checked. I don't think it's an issue with the names of the elements (though I do realize the naming style is not consistent, however, I don't have full control over that). I'm assuming it's just me making a simple mistake in the code and I still don't have enough experience with javascript to catch it yet. Anyone see what I'm doing wrong?
Thank you for your time!
You're assigning your click handlers like this:
$('0_exclusive_2176').onclick = allow(0,[1975]);
What's happening is: allow is ran and its return value (undefined) is set as the event. You need to set onclick to a function:
$('0_exclusive_2176').onclick = function(){
allow(0,[1975]);
};
You can also make allow return a function:
function allow(i, extended){
return function(){
$('[id^="'+i+'Extended"]').disabled = true;
for (var j = 0; j < extended.length; j++) {
alert(extended[j]);
$(i+"Extended"+extended[j]).disabled = false;
}
};
}
Now $('0_exclusive_2176').onclick = allow(0,[1975]); should work as expected.

Limit Count of Multiselect HTML PHP

How can I limit the count of multiselect? Like I want the user to select atmost 3 elements from multiselect. If more than 3 are selected then I ll throw him an error...
Here is a complete example, showing the HTML of a simple form and the PHP that only allows up to three options being selected - and an added bonus of client-side JavaScript to explain how the user can be informed of their error before the form is submitted.
You can use JavaScript to stop the user checking more than three options, but note that client-side validation can easily be avoided, so you will still need to use PHP to verify on the server.
HTML
<!doctype html>
<head>
<meta charset="utf-8">
<title>Multiselect example</title>
</head>
<p>Please make a selection below (maximum three options!)</p>
<form method="post">
<select name="selection[]" multiple="multiple">
<!-- Put <option> elements here -->
</select>
<input type="submit">
</form>
<script src="Script.js"></script>
JavaScript (in Script.js):
var formChange = function(e) {
var i,
num = 0,
// Obtain a list of all selected options:
nodeList = this["selection[]"];
// Loop over all options, count how many are selected.
for(i = 0; i < nodeList.length; i++) {
if(nodeList[i].selected) {
num ++;
}
}
if(num > 3) {
alert("Please do not select more than three options");
e.preventDefault();
}
};
// Attach the same function to the change and submit event.
// This will alert the user of more than three selections
// as the fourth is selected, or as the form is submitted.
// ... it will also not allow the form to submit with
// more than three checked boxes.
document.forms[0].addEventListener("change", formChange);
document.forms[0].addEventListener("submit", formChange);
PHP:
if(isset($_POST["selection"])) {
if(count($_POST["selection"]) > 3) {
die("Error: More than three check boxes were checked.");
}
// $_POST["selection"] is an array of the checked values.
}
A multiselect element in PHP returns an array, so it's simply a matter of comparing the count() of the returned array against the maximum value you want to allow and generating some kind of error if the count exceeds the limit (throw an exception, trigger an error, etc).
If you want to do it server-side, look at the count() function. E.g.,
HTML:
<form ...>
<select name="options[]" multiple="multiple">
<!-- options here ... -->
</select>
...
</form>
PHP:
<?php
if (isset($_POST['options']) && count($_POST['options']) <= 3) {
// OK
} else {
// Not OK
}
?>
Take a look at this js function, suppose your multiselect object is "muSelect"
function checkSelected() {
var i;
var count = 0;
for (i=0; i<muSelect.options.length; i++) {
if (muSelect.options[i].selected) {
count++;
}
if (count > 3) {
alert("cant select more than three options";
// any other additionnal processing
}
}
}
and then you can add this function as onClick event
I know that this is an old question but if someone is trying to do the same thing now and looking for answers is best to write a current answer for this one. The best way at the moment is with AJAX (as long as I know):
HTML: form.html
<form id="myForm" action="validate.php?q=1">
<select name="options[]" multiple="multiple">
<!-- options here ... -->
</select>
...
</form>
PHP: validate.php
<?php
switch($_REQUEST['q']){
case 0:
if(isset($_REQUEST['options']) && count($_REQUEST['options']) <=3){
echo true;
}else{
echo false;
}
break;
case 1:
if(isset($_POST['options']) && !empty($_POST['options'])){
if(count($_POST['options']) <= 3){
//OK
}else{
//NOT OK
}
}
break;
}
?>
JavaScript(jQuery): script.js
var form = $("#myForm");
var options = $("#select_menu option")
var selected = [];
$(options).each(function(key,option){
if(option.selected){
selected[key] = option;
}
});
$.ajax({
url: "validate.php",
method: "GET",
data: {
options: selected,
q: 0
},
success: function(Response){
if(Response === true){
//OK
}else{
//NOT OK
}
}
});
Please correct me if I have error somewhere.

Categories