Check checkbox and set value on load content/page - javascript

I have a some shop. In cart (when usually user is not logged) is checkbox for set Invoice. If is not checked - then user get a bill.
On next step, user has to login, and goes to Procced page. When user goes ahead (after login page), can't change checkbox without back to cart.
I need to check (after login, on procced page) Customer is Company or normal user (private) and if user is Company, set the invoice as default.
I have that code:
(I know is not pure php - is some kind of framework)
<!-- CART PAGE with checkbox -->
<div id="additionalRealizationInfo">
?{foreach system.cart.optionsData option}
<label>
<input class="additionalRealizationInfoCheckbox"
type="checkbox"
?{if true == option.option.enabled}
checked="checked"
?{endif}
name="additional?{=system.randomNumber}"
value="${system.controllerUrl}ToggleOption/?{=option.name}" />
?{=option.title}
</label>
?{endforeach}
// The Value of checkbox is: toggleOption/facture
<!-- PROCCED PAGE without checkbox - On this page, after login, user see own choice from cart before login -->
<div id="additionalRealizationInfo">
<h2>Infos</h2>
<div>
?{foreach system.cart.optionsData option}
<div>
?{if true == option.option.enabled}
You get Invoice
?{else}
You get recive
?{endif}
</div>
?{endforeach}
</div>
</div>
<script type="text/javascript">
var isCompany = "?{=system.userLogged.InvoiceData.company}"; <!-- Company Name -->
var enableInvoice = "?{=system.cart.invoiceEnabled}";
if (isCompany.lenght > 0) {
$.get("${system.controllerUrl}setInvoiceEnabled",function(resp) {
$.get("${system.baseUrl}view/enableinvoice",function(resp) {
$("#additionalRealizationInfo").html(resp);
});
});
$.get("${system.controllerUrl}toggleOption/facture",function(resp) {
});
};
</script>
// string to check choice: ?{if system.cart.invoiceEnabled}
// system.baseURL/view/enableinvoice is some code to show, that invoice is set default (when script works)
What's wrong. It doesn't work

At first glance, I'd examine this line of code:
if (isCompany.lenght > 0) {
You've misspelled length. Try this:
if (isCompany.length > 0) {
OR, depending on if the value of the "isCompany" variable is true/false, you could write it as
if (isCompany) { // check boolean value instead
Hope that helps!

I change the script and it works, but only after I reload/refresh a page.
<!-- CART PAGE before and after login -->
var companyCustomer = "?{=system.userLogged.InvoiceData.company}";
//If user is logged, companyCustomer has a value. If not = ""
var enableInvoice = "?{=system.cart.invoiceEnabled}";
// If true = "1" , If false = "". That's not a boolean string.
var klik = $("#additionalRealizationInfo>label:first-child>input:checkbox");
if (companyCustomer) {
klik.prop('checked', true);
klik.prop("disabled", true);
klik.css('cursor','default');
$.get("${system.controllerUrl}toggleOption/facture",function(resp){
console.log(resp);
});
}; // End if (companyCustomer)
<!-- PROCEED PAGE after login -->
var companyCustomer = "?{=system.userLogged.InvoiceData.company}";
//If user is logged, companyCustomer has a value. If not = ""
var enableInvoice = "?{=system.cart.invoiceEnabled}";
// If true = "1" , If false = "". That's not a boolean string.
if (companyCustomer) {
if (enableInvoice) {
} else {
$.get("${system.controllerUrl}toggleOption/facture",function(resp){
console.log(resp);
});
}; // end if (enableInvoice)
}; // end if (companyCustomer)
How it execute on load, and dynamically change/set this toggle option?
When I didn't check the checkbox in CART PAGE, go next to login, and automatically go to PROCEED PAGE I get
enableInvoice = "";
I tried .ready and .load() and .live() and nothing works. Tried execute by .click but I don't want this method. I don't want to also refresh page after content shows up.

Related

Progress bar indicating form completion in jQuery

I'm working on a progress bar using the progress element that increases as the user completes fields in a lengthy form. I found this SO thread which was helpful in getting some baseline functionality using a data-* attribute, but my form has a "Save Progress" feature that will save any entered field information to the browser's local storage to be retrieved later. Thus, in the event that a user returns to the form with saved data, I'd like the bar to reflect that level of progress.
Here's what is working thus far- sample markup using the data-attribute data-prog for a form field:
<!-- FORM - SAMPLE FIELD -->
<div id="form">
<div class="field-group required">
<label for="mgd_org_name">Organization Name:</label>
<div>
<input id="mgd_org_name" type="text" name="mgd_org_name" placeholder="Please enter your organization's name" required data-prog="6">
</div>
</div>
</form>
<!-- Progress bar -->
<div id="form-progress">
<p>Form Progress</p>
<progress max="100" value="0" id="progress"></progress>
</div>
And the jQuery thus far:
$(function() {
// get all form inputs w/ data-prog values
var inputs = $('#dossier-form').find('input[data-prog], textarea[data-prog]');
var progBar = $('#progress');
var progVal = 0;
$(inputs).change(function() {
if ($(this).val().length > 0) {
progVal += $(this).data('prog');
progBar.attr('value', progVal);
}
});
});
In this way, each field has a data-prog value that will be added to the progVal and reflected in the progress bar level. What I'm having trouble with is loading an initial value for any form fields that might already be filled on load—thus, I would need to find all fields that have a value entered, add the associated data-prog values, and initially load that value into the progress bar. I would also like to accordingly decrease the progress value in the event that a field is cleared.
For the initial load, I've been trying something like the following (not working):
var inputsSaved = $(inputs).val();
if($(inputsSaved).length > 0) {
progVal = $(inputs).data('prog');
console.log('has existing progress');
} else {
progVal = 0;
console.log('does not have existing progress');
}
I'm not quite sure how to find the fields with text entered on load and grab the associated prog values nor how to decrease the value accordingly if a field is cleared. Any assistance here is greatly appreciated!
First, your inputs selector can be replaced by:
var inputs = $('#dossier-form [data-prog]');
Then, $(inputs).change(..., inputs already is a jQuery object. No need to wrap it with $().
You had the progress update function correct. I just placed it in a named function to be able to call it from different places in code (and avoid duplicate code).
I added the localStorage save and retreive...
$(function() {
// get all form inputs w/ data-prog values
var inputs = $('#dossier-form [data-prog]');
var progBar = $('#progress');
var progVal = 0;
// Establish the "dificulty unit" base.
var totalDifficulty = 0;
inputs.each(function(){
totalDifficulty += $(this).data('prog');
});
var difficultyUnit = 100/totalDifficulty;
// Update progressbar
function updateProgress(el){
progVal += parseFloat($(el).data('prog')) * difficultyUnit;
progBar.val(progVal);
}
// LocalStorage on load
inputs.each(function(){
var value = localStorage.getItem(this.id);
if(value !=null && value !=""){
$(this).val(value);
updateProgress(this);
}
}); // End load from LocalStorage
// Blur handler to save user inputs
inputs.on("blur",function(){
// Reset the progress
progVal = 0;
progBar.val(progVal);
// Loop through all inputs for progress
inputs.each(function(){
if ($(this).val().length > 0) {
updateProgress(this);
}
// LocalStorage
localStorage.setItem(this.id,this.value);
});
}); // End on blur
}); // End ready
localStorage isn't allowed in the SO snippets... So have a look at this CodePen.
So you can now give some "difficulty level" without worring about the total obtained by all the data-prog to be 100. Just give an arbitrary number you feel like. ;)
If you always add up the progress from scratch, you can do the same thing in both cases.
$(function() {
// get all form inputs w/ data-prog values
var inputs = $('#dossier-form').find('input[data-prog], textarea[data-prog]');
var progBar = $('#progress');
function update () {
var progVal = 0;
inputs.each( function () {
if ($(this).val().length > 0) {
progVal += Number( $(this).data('prog') );
}
})
progBar.attr('value', progVal);
}
inputs.change( update );
// Fill in fields from localStorage, then:
update();
});

ASP.NET MVC 4 Having trouble selecting the correct input element using js/jquery

I'm working with a form that I've built using HTML helpers, like so:
#using (Html.BeginForm("CreateNewRoom", "Admin", FormMethod.Post, new { #enctype = "multipart/form-data", #class = "form-vertical", style = "margin-top:-30px" }))
{
<fieldset>
<legend>Create a new Room</legend>
<div class="form-toolbar sepa">
<label class="darkBlue toolbar-label">Room name:</label>
<div>
#Html.TextBoxFor(x => x.name, new { #id = "room", #class = "form-control-static", #style = "margin-bottom:5px;", #autofocus = "true" })
</div>
</div>
...
<div class="form-toolbar sepa">
<label class="darkBlue toolbar-label">Display:</label>
<div>
#Html.RadioButtonFor(x => x.display, "True") Yes&nbsp
#Html.RadioButtonFor(x => x.display, "False") No&nbsp
</div>
...
Just in case it helps, Chrome DevTools informs me that this is the HTML being displayed by my radio button helper:
<input id="display" name="display" type="radio" value="True">
" Yes "
<input checked="checked" id="display" name="display" type="radio" value="False">
" No "
I have a Javascript file which dynamically plays with the elements on the page. I would like for js to add a class to an element on the page, to simply change its opacity to 0.5, if it finds that the "No" radio button is selected.
if ($('input[name="display"]').val() === "False") {
if (($('#selectedRoomName')) && ($('#selectedRoomArrow')))
$('#selectedRoomName').addClass('obscured');
$('#selectedRoomArrow').addClass('obscured');
} else {
//sad
}
I've used this block in $(document).ready and in $(input[name="display"]).change, to make js add the class if display is 'False' when the page loads, and also to add it if the 'False' radio button is selected.
However, I found that js had a problem reading the value of the input, and thinks that it is true almost all the time, even if the false button is selected. I'm assuming it must be something to do with the fact that the two inputs have the same name?
My question is, how do I ensure that js always picks the input that is currently selected, and will this make sure that it reads the correct value?
UPDATE: I have changed $('input[name="display"] to $('input[name="display"][checked="checked"]'), in an effort to make js home in on whichever radio button is checked. This solves the problem where js did not know which button was checked on page load. However, now it always targets whichever button was checked on page load, instead of the button that's actually checked currently.
Apologies if I seem like a complete novice, but I am, so...
Any and all suggestions on how to better organise my code are welcome; I'm very unfamiliar with best practises in web dev.
Thanks!
Just change the following line in your change event from :
if ($('input[name="display"]').val() === "False") {
to:
if ($(this).val() === "False") {
This will check for the value of the radio button that is current clicked.
I used a combination of #Ehsan's answer, and a partial solution that I included in an update to the the question.
I decided to place the js block in a function, which took the element whose value I was checking as a parameter:
function checkdisplay(dispradio) {
var a = document.getElementById("selectedRoomName");
var b = document.getElementById("selectedRoomArrow");
if ((a) && (b)) {
if (dispradio.val() === "False") {
a.className += " obscured";
b.className += " obscured";
} else {
a.className = a.className.replace(/(?:^|\s)obscured(?!\S)/g, '');
b.className = b.className.replace(/(?:^|\s)obscured(?!\S)/g, '');
}
}
}
Then I called the function in two places like so:
//first for document load
$(document).ready(function () {
checkdisplay($('input[name="display"][checked="checked"]'));
});
and
//and then for change events
$('input[name="display"]').change(function () {
checkdisplay($(this));
});
Seems like [checked="checked"] was needed to let js know which button was checked on page load, but that then needed to be removed for onchange events, or js would target whichever button was checked on page load, rather than the button that was actually checked!
Many thanks for your partial solution #Ehsan, it helped me come up with this one!

Create button which takes to a particular URL according to data in Form Field

I've two input form fields and i want when the user clicks a submit button he should be taken to a URL based on the input in these two fields. For example if the input in the two input fields is A and B respectively the condition should be set such that the User is taken to www.mydomain.com/C in Javascript. I DON'T want the values to be appended to the URL like www.mydomain.com/a/b which I already know how to.
I have seen lot of questions on SO and Google on URL Generation but none was the case as mine. I would really appreciate help from fellow SO users. Thanks in advance.
Do you mean something like this? This would take you to the address when both inputs have the value 'something' and the button is clicked.
<input type="text" id="a">
<input type="text" id="b">
<button onclick="go()">Go</button>
<script>
function go() {
if (document.getElementById('a').value == 'something' && document.getElementById('b').value == 'something') {
window.location = 'http://www.example.com/C';
}
}
</script>
If you are using jquery:
$( "form" ).submit(function() {
// TODO read your variables
// TODO apply conditions and redirect accordingly
if ( ... ) {
window.location = 'http://www.example.com/C'
} else {
window.location = 'http://www.example.com/D'
}
return false; // prevent default submit
});

jQuery script fails executing for some of the users

I am using a custom form to submit data to Google Spreadsheets. When user attempts to submit the form, it is validated (with jQuery) and if the validation is passed, the main input field is being modified with jQuery and then the submission continues.
The user inputs a URL and during submission the script cuts off unnecessary parts of the link and adds IP (that is also gathered with jQ) of the user to it. After the modification is completed, the form continues submission and in result, only the modified data is being sent to Google Spreadsheet.
It works pretty well with 99% of submissions but there are several users whose browsers do not execute the script properly; i.e.: the URL they input is not being modified during the submission and thus, wrong data (unmodified) is sent to the Spreadsheet. I am not completely sure, but the problem may be caused by Firefox (but I am not 100% sure that all the faulty submission come from Firefox, if you want I could research and confirm whether it is only Firefox's issue). I have asked some of them (users, whose browsers seem not to execute script) about addons/if they had turned JS off but they say they did not do anything special with their browsers.
I am posting whole js file below so you could check whether I did some errors that could cause problems. Also, the script is running here (link), you can inspect the code to see what other jQuery stuff I use.
$(document).ready(function() {
//Tabbiing page is being initialised, doesn't really matter, I think
$.ionTabs("#fppp_taby");
//Script that checks whether user has been redirected back after submission, that's not the main problematic part yet
if (window.location.search != 0) {
var query = window.location.search.substring(1);
ideo = query.split("=")[1];
if (isNaN(ideo) || (ideo.length < 3) || (ideo.length > 10)) {
$("form").html("Wystąpił błąd podczas wysyłania Twojego zgłoszenia. Powiadom mnie o tym poprzez prywatną wiadomość podając również obecną godzinę za pomocą <a class='uline' href='http://www.erepublik.com/pl/main/messages-compose/2417512'>tego linka</a>.");
} else {
$("form").html("Dziękujemy za zgłoszenie!<br /><br />Możesz teraz przeczytać któryś z artykułów epolskiej prasy - lista wartch uwagi znajduje się po lewej stronie!");
var poZglosz = "Dziękujemy za zgłoszenie!<br />Spodziewaj się chlebków i broni od któregoś z tych graczy: Kijek93, twatwaratwa, Gregoric bądź Zawa99";
$("#poZglos").html(poZglosz);
$("#poZglos").removeClass();
}
} else {
var query = 0;
}
//Some simple stuff
$("#wlaczirc").click(function() {
$(this).hide();
$("#irc").html("<iframe src='http://webchat.quakenet.org/?channels=fppp&uio=OT10cnVlJjExPTM0OQ1f'></iframe>");
$("#irc").show("slow");
$("#info_irc").show("slow");
});
//Some data
infoPodkr = "Wklej tutaj prawidłowy link do twojego profilu!";
inputLink = $("#ffpolelinku");
//Resetting validation info in input
$(inputLink).focus(function() {
if ($(this).hasClass("podkresl") || $(this).val() == infoPodkr) {
$(this).val("");
$(this).removeClass("podkresl");
}
});
//Gathering ip
$.getJSON("http://jsonip.com/",
function(data) {
ip = data.ip;
});
//MAIN PART (executed when user pressses 'submit')
$("form").submit(function() {
//Form is being hidden (display:none class is being added)
$('aside').addClass("hidden");
//Check whether input is empty or contains error message (infoPodkr = error message vlaue), if yes, add class 'podkresl'
if (($(inputLink).val() == "") || ($(inputLink).val() == infoPodkr)) {
$(inputLink).addClass("podkresl");
$(inputLink).val(infoPodkr);
} else {
$(inputLink).removeClass("podkresl");
}
//Tesing whether user added proper link, if not, 'podkresl' is added
//if (!/\b(https?|ftp|file):\/\/[\-A-Za-z0-9+&##\/%?=~_|!:,.;]*[\-A-Za-z0-9+&##\/%=~_|]/.test(inputLink.val())){
if (!/http\:\/\/www\.erepublik\.com\/[a-z]{2}\/citizen\/profile\/\d{5,}$/i.test(inputLink.val())) {
$(inputLink).addClass("podkresl");
$(inputLink).val(infoPodkr);
}
//Split link, and get the last part of it ('wycId'), check if it's numeral, if not - add 'podkresl' class
podzielony = $(inputLink).val().split('/');
wycId = podzielony.pop();
if (isNaN(wycId)) {
$(inputLink).addClass("podkresl");
$(inputLink).val(infoPodkr);
}
//Check whether the input class 'podkresl' class (= something was wrong in some of the steps above). If yes, remove the 'hidden' class from 'aside' which holds the form and show it to the user. If there were no errors, add the IP to the 'wycId' and additional "-n" to the end of the value and put it into input. Then, submit form.
if ($(inputLink).hasClass("podkresl")) {
$('aside').removeClass();
return false;
} else {
if (ip !== '') {
$(inputLink).val(wycId + "-" + ip + "-n");
} else {
$(inputLink).val(wycId + "-0-n");
}
}
return true;
});
});

How to repopulate form variables?

I've got a page that should warn if the user tries to leave the page having unsaved data. This dialog means "You have unsaved data. Do you want to conitnue?"
The problem is that the form values go blank when the user clicks a link to move on and is presented with the dialog. I want to form values to stay in place so that the user actually can choose not to continue and then still have left what was entered to the form.
The way the code is now is that it keeps a flag for whether the form has dirty data and that is a hidden variable:
<input type="hidden" name="saveStatus" value="<%=saveStatus%>" />
Touching the form sets this hidden variables with onclickand onkeypressed.
On the server I've got some logic that checks whether data is dirty:
public boolean returnToUnsavedData(ISessionHandler sessionHandler,
Action action) {
String saveStatus = sessionHandler.getRequestParameter("saveStatus");
if (saveStatus != null && !saveStatus.trim().equals("")) {
setHasUnsavedData(true);
} else {
setHasUnsavedData(false);
}
if (hasUnsavedData()) {
if (!"menuHasUnsavedDataOk".equalsIgnoreCase(action
.getActionCommand())
&& !action.getActionName().equals("Administrera")) {
ResourceBundle messages = ResourceBundle.getBundle("messages");
UserMessage um;
if (action.getActionCommand().equals("fastsearch")) {
um = new ExtendedUserMessage(
messages.getString("PV24"), UserMessage.TYPE_WARNING,
"Varning", action.getActionName(),
action.getActionCommand(), sessionHandler.getRequest().getParameter("fastsearch"));
} else {
um = new ExtendedUserMessage(
messages.getString("PV24"), UserMessage.TYPE_WARNING,
"Varning", action.getActionName(),
action.getActionCommand());
}
action.addUserMessage(um);
action.setReturnPage(action.getCurrPage());
setLatestActionTarget(action.getActionTarget());
return true;
} else {
setHasUnsavedData(false);
}
}
return false;
}
I suppose this is where I could check serverside for the variables and repopulate everything and then use a technique like above with the hidden variable to keep form values.
Do you think that this idea will work or can you present alternative solutions?
I don't think you need server-side involvement here, you can achieve this by using just javascript:
<input type="hidden" id="saveStatus" name="saveStatus" value="<%= saveStatus %>"/>
Register an observer before the page gets unloaded and check your saveStatus variable in there:
window.onbeforeunload = function() {
if (document.getElementById('saveStatus').value) {
return 'You have unsaved changes, are you sure you want to leave the page?');
}
};
However, by using this you will not have your own 'custom' confirmation screen, the browser's built in confirmation will be used (similar to stack-overflow's).

Categories

Resources