Setting default option and disabling alert - javascript

I've been trying for some time now to get this to work. I don't have much experience with jquery or javascript. I want to set a default option that is selected from the drop down options when the button is pressed. I hope this will also prevent the alert(not sure if that's correct) from appearing. I have add the following code to the "code injection" part of squarespace, which seems to work fine. (Edited, I have removed the code as recommend)
I'm using the Brine template. Here's a link to the website https://www.metastudio35.com/private-photography-services/event-collection the password is "Google360".
<squarespace:script src="plugin.js" combo="true"?>
<squarespace:script src="site.js" combo="true"?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
I then added the code below in the page I needed to redirect the button. Which also works, but without the "$("#Additional Photos").val("0");" and "$( ".sqs-widgets-confirmation-content clear" ).dialog( "close" )" lines.
<script>
$(document).ready(function(){
$("#Additional Photos").val("0");
$( ".sqs-widgets-confirmation-content clear" ).dialog( "close" )
$(".sqs-add-to-cart-button").click(function(){
window.location = '/booking/';
});
});
</script>
This is a screenshot of the dialog box I want to remove/disable.
dialog box pop up screenshot
If someone could point me in the right direction or tell me what I'm doing wrong it would be greatly apprenticed.
Thank you for your help.

I checked your website and it seems like jQuery is not used by your template, and instead of including jQuery just for this simple function, I've written the below code in vanilla JS instead.
function setValue() {
var dropdown = document.querySelectorAll('[data-variant-option-name="Additional Photos"]')[0];
dropdown.value = '0';
Y.one('#'+dropdown.id).simulate('change');
}
window.onload = setValue;
If you're interested in figuring out why your code wasn't working, here's the explanation :
$('#Additional Photos').val("0")
This line of code is setting the element that has an ID of "Additional Photos" with a value of "0".
Your "Additional Photos" select box does not have an ID of "Additional Photos", instead - it has a randomly generated ID that re-generates each time the page is refreshed.
So the reason that your code isn't working is because you're simply targeting the wrong element :)
var dropdown = document.querySelectorAll('[data-variant-option-name="Additional Photos"]')[0];
Due to the fact that the ID of the select box is not constant, we are targeting the select box by the 'data-variant-option-name' attribute instead. I figured out this constant attribute simply by inspecting the selectbox on the ChromDev tools.
dropdown.value = '0';
Y.one('#'+dropdown.id).simulate('change');
The other thing to consider is the fact that your template is using YUI to handle the select box. This means that we need to manually trigger the 'change' event in order for the UI to update. As you can see from the code above, the first line is setting the value of the select box, while the second is telling YUI to simulate the 'change' event, and thus - updating the UI.
Hope this helps !

Related

check box validation javascript

I need to validate the selection of at least one check box on a table. I am not using an alert because I already have a class on CSS that highlights in red the inputs, selects and other elements if they are not filled out.
This is my JS:
var btnRegister= document.querySelector('#btnRegisterRegObr');
btnRegister.addEventListener('click', function () {
var bError= false;
//I am initializing this boolean variable so that it also shows an error
//message on the screen if the user has not selected any option at all...
var elementCheckRegObr = document.querySelector('#checkRegObr');
if (elementCheckRegObr.checked==false){
bError=true;
elementCheckRegObr.classList.add('error');
//This part of the code brings the error I have
//previously created on CSs if the checkbox is not checked
}
else{
elementCheckRegObr.classList.remove('error');
}
});
The button on HTML has the right id on the HTML: id="btnRegisterRegObr.
I was looking at some codes here and people were validating using the .checked==false
However this does not seem to work for mine.
As a matter of fact, I first thought I needed to use the syntax of if (elementCheckRegObr.checked=="") but that one does not seem to work either.
I dont have problems validating inputs, selects nor radio buttons, but I am not sure if I am doing it on the right way with the check boxes. Any help or advice would be greatly apprecciate it :)
I suggest that you use getElementById to get your elements, and test if the checkbox is checked this way:
if(document.getElementById('idOfTheCheckBox').checked){
alert('hey, im checked!');
}

Show sections based on value of Check box in jQuery (SharePoint 2010)

I am trying to use jQuery to show section if a user selects a certain checkbox in a sharepoint form. I have had success doing this with a button and with a simple checkbox with one value to show all from this blog post http://akanoongo.blogspot.com/2008/04/how-to-hide-fields-in-sharepoint-list.html, but am struggling with if they select multiple values.
<script type="text/javascript" src="/SiteAssets/Libraries/jquery-1.10.2.min.js"></script>
<script>
$(document).ready(function(){
$("nobr:contains('Desk Calendars')").parent('h3').parent('td').parent('tr').hide();
$("nobr:contains('Calendar Refills')").parent('h3').parent('td').parent('tr').hide();
$("nobr:contains('Spiral Bound')").parent('h3').parent('td').parent('tr').hide();
$("nobr:contains('Wall Calendars')").parent('h3').parent('td').parent('tr').hide();
$("nobr:contains('Misc. Calendars')").parent('h3').parent('td').parent('tr').hide();
$("nobr:contains('Franklin Covey')").parent('h3').parent('td').parent('tr').hide();
$("nobr:contains('Comments')").parent('h3').parent('td').parent('tr').hide();
$("nobr:contains('Retention Policy')").parent('h3').parent('td').parent('tr').hide();
});
</script>
It would appear the value needs to be an if statement for contains VALUE not a click function. I am not sure what to do with this though.
$("input[title$='ShowFields']").click(function()
Basically if they select Wall Calendars it should show jsut wall calendar but if they do Wall and desk, it should toggle them both.
Any guidance would be fantastic. Thank you!
EDIT: I change my answer based on your comment below
To do what you want I'll use the library I created that is called SharepointPlus (please load jQuery and SharepointPlus in your page). Then the JavaScript code would be something like:
// hide all the rows by default
$SP().formfields("Desk Calendars,Calendar Refills,Spiral Bound,Wall Calendars,Misc. Calendars,Franklin Covey,Comments,Retention Policy").row().hide();
// add a trigger for when you click a checkbox
$SP().formfields("Calendar Type").elem().on('click', function(event) {
// the value of the checkbox is found with the "title" attribute from the parent
// if it's checked, then we show the row, if it's not then we hide it
$SP().formfields($(this).parent().attr("title")).row().toggle(this.checked)
})

value from dropdown show/hides div and keeps its state

im relatively new to ROR, and would like some help with the following code.
I would like to show a div (it's called demographics) when a specific selection ("Customers") is made form a dropdown. If an option other than "Customers" is selected from the dropdown, I would like that the demographicsv div remain hidden.
At present, my code is partially working. It shows and hides the div; however, when I save the page and come back to it, the div is hidden, even if "Customers" is selected in the dropdown. This might be because the default setting is: display:none.
Is there a way to make sure that the field is displayed on page load when the proper selection has been made?? And I suppose a way to make the opposite true too--> a div with display:block; remains hidden if the field from the dropdown does not match the required field.
Any help would be extremely appreciated. Thank you and I sincerely appreciate your time:
my code (HAML):
= f.select :who, WHO, {}, :onChange => "showDemographics(this)", :prompt => true
#demographics{:style => "display:none;"}
%p.information
please fill out the following demographics.
%div{:class => "label_leftalign field"}
= f.label :age, "Age"
= f.select :age, AGES, :prompt => true
%div{:class => "label_leftalign field"}
= f.label :race,
= f.select :race, RACES, :prompt => true
Javascript
function showDemographics(obj)
{
if(obj[obj.selectedIndex].value == 'Customer')
{
document.getElementById('demographics').style.display = 'block';
}
else
{
document.getElementById('demographics').style.display = 'none';
}
}
EDIT::
OK, So the key issue is that on page reload a div remains hidden even if the correct value is in the dropdown box. I suppose that this can be solved by one of two ways 1. running some sort of validation on everytime the page is loaded or 2. cookies.
Unfortunately, I'm not very well versed in Javascript or jQuery... and I've never implemented cookies on a site, and would prefer to avoid using them if possible.
Could anyone help me write a script that validates the presence of Customer in the dropdown and shows/hides a div accordingly? Thank you, and thanks to Carlos Pardilla and M. Cypher for their help thus far.
You have tagged the question with jQuery although you're not using it in the code, but I'll just assume it's fine if I give you some jQuery code:
$(function() {
$('#who').change(function() {
if ($(this).val() == 'Customer') {
$('demographics').show();
} else {
$('demographics').hide();
}
}).change();
}
Note that you need to give the select an id (in this case who) for it to work.
I guess you could use a conditional statement to be checked during page load. You could establish the visibility (or lack thereof) of the div depending on the value ("Customers") of the option:selected element within your select object (the dropdown). Maybe via a script on the head of the document (provided it is a short script). Also, by doing this you wouldn't need to set the display property from the start. It would fire depending on the selected condition during page load.
This could be done to get the opposite result as well, as you said.
Hope it'll help!
The answers above where correct in their own way... the link below shows the actual code that is required for the conditional statement on page load:
show hidden divs on refresh

set value to jquery autocomplete combobox

I am using jquery autocomplete combobox
and everything is ok. But I also want to set specific value through JavaScript like $("#value").val("somevalue") and it set to select element, but no changes in input element with autocomplete.
Of course, I can select this input and set value directly, but is it some other ways to do that? I try set bind to this.element like this.element.bind("change", function(){alert(1)}) but it was no effects. And I don't know why.
Edit
I found a workaround for this case. But I don't like it. I have added the following code to _create function for ui.combobox
this.element.bind("change", function() {
input.val( $(select).find("option:selected").text());
});
And when I need to change the value I can use $("#selector").val("specificvalue").trigger("change");
Is this demo what you are looking for?
The link sets the value of the jQuery UI autocomplete to Java. The focus is left on the input so that the normal keyboard events can be used to navigate the options.
Edit: How about adding another function to the combobox like this:
autocomplete : function(value) {
this.element.val(value);
this.input.val(value);
}
and calling it with the value you want to set:
$('#combobox').combobox('autocomplete', 'Java');
Updated demo
I cannot find any available existing function to do what you want, but this seems to work nicely for me. Hope it is closer to the behaviour you require.
I managed a quick and dirty way of setting the value. But, you do need to know both the value and the text of the item that you want to display on the dropdown.
var myValue = foo; // value that you want selected
var myText = bar; // text that you want to display
// You first need to set the value of the (hidden) select list
$('#myCombo').val(myValue);
// ...then you need to set the display text of the actual autocomplete box.
$('#myCombo').siblings('.ui-combobox').find('.ui-autocomplete-input').val(myText);
#andyb,
i think rewrite:
autocomplete: function (value) {
this.element.val(value);
var selected = this.element.children(":selected"),
value = selected.val() ? selected.text() : "";
this.input.val(value);
}
I really like what andyb did, but I needed it to do a little more around event handling to be able to handle triggering the a change event because "selected" doesn't handle when hitting enter or losing focus on the input (hitting tab or mouse click).
As such, using what andyb did as a base as well as the latest version of the jQuery Autocomplete script, I created the following solution: DEMO
Enter: Chooses the first item if menu is visible
Focus Lost: Partial match triggers not found message and clears entry (jQuery UI), but fully typed answer "selects" that value (not case sensative)
How Change method can be utlized:
$("#combobox").combobox({
selected: function (event, ui) {
$("#output").text("Selected Event >>> " + $("#combobox").val());
}
})
.change(function (e) {
$("#output").text("Change Event >>> " + $("#combobox").val());
});
Hopefully this helps others who need additional change event functionality to compensate for gaps that "selected" leaves open.
http://jsfiddle.net/nhJDd/
$(".document").ready(function(){
$("select option:eq(1)").val("someNewVal");
$("select option:eq(1)").text("Another Val");
$("select option:eq(1)").attr('selected', 'selected');
});
here is a working example and jquery, I am assuming you want to change the value of a select, change its text face and also have it selected at page load?
#
Attempt 2:
here is another fiddle: http://jsfiddle.net/HafLW/1/ , do you mean that you select an option, then you want to append that value to the autocomplete of a input area?
$(".document").ready(function(){
someString = "this,that";
$("input").autocomplete({source: someString.split(",")});
$("select").change(function(){
alert($(this).val()+" appended");
someString = someString+","+$(this).val();
$("input").autocomplete({source: someString.split(",")});
});
});

$().buttonset not working on dialog modal box

I've done a dialog box that contains a form inside it, and I would like to add some fancy items to it. I've been trying with $().buttonset() as I've done with most of my radio buttons in the application, in order to get a coherent UI for my application. The thing is that, even if following the rules specified, the buttons remain as a normal radio button, and not with the fancy interface. Do you know what could be the problem?
This is the part of the form where I want the fancy radio buttons:
<div id ="Replace">
<input type="radio" name="Replace" value = "true" id = "ReplaceYes"
onclick = "setReplace(this)" />
<label for="ReplaceYes">Yes</label>
<input type="radio" name="Replace" value = "false" checked="checked"
id = "ReplaceNo" onclick = "setReplace(this)" />
<label for="ReplaceNo">No</label>
</div>
And then, as the previous part of code is in a partial view, invoked when showing the modal box, this is how I try to convert the buttons appearance:
$("#Replace").buttonset();
The thing is that, debugging it I've seen that it goes through that part of the code, but it doesn't do what it's meant to do. Any clue?
I had the same problem has your, after an intensive reflexion I 've found that :
When you declare your Dialog box, you can specify a function called when it opens
$( ".selector" ).dialog({
open: function() {
$( '#buttonset' ).buttonset();
}
});
Updated: I had never used .buttonset() before, in any case it works against your markup, you can see a demo here. This demo uses the same code as the question:
$("#Replace").buttonset();
Make sure you're including the jQuery UI CSS correctly, and that your IDs are unique, if they are not you'll get some real funny behavior, and should switch to a class. Also, ensure that this part of your view is in the DOM when it runs, e.g. is it inside a document.ready event handler like this?
$(function() {
$("#Replace").buttonset();
});

Categories

Resources