Javascript alert still shows after condition changed - javascript

I am building a web page where one must select an input from a list and then hit a button which takes to you a new page based on that selection. If nothing from the list is selected and this button is pressed, I want the user to be alerted that they must select from the list before proceeding.
So my initial HTML has a blank href:<a id="Button" href="">Start</a>
Then I add this href via js after list selection:
choice.mousedown(function(){
if (this.data('fullname')=='X'){
document.getElementById('Button').href = '/newpageX';}}
This all works fine and adds the href to the button exactly as desired. The problem comes when I next try to add the alert when the href is still emtpy. So after the js code above, in order to alert the user if this href is still blank (ie nothing chosen from list) and they hit the button, I added a check as follows (using jquery):
document.getElementById('Button').onclick = function () {
if ($('Button').attr('href') === undefined) {
alert('Please select an option from list above');}}
This does seem to work fine when nothing has been selected, but if a user does select something from list, this alert still shows anyway before it then correctly proceeds to the new page based on list selection (newpageX)! This is my main problem. So it's as if the condition of the href (defined/undefined) isn't re-checked via the jquery if statement after the href is defined via the list choice - and beause of this the alert still shows anyway. What am I doing wrong? How can I prevent the alert from showing if in fact the href is now defined based on the list selection? Is there a better overall strategy here?
Also, separately - when href is in fact empty and the button is pushed, after one hits 'ok' on the alert, the page is reloaded. I don't believe this is necessary - how can I just have the alert show, but not reload the page? I tried to add 'return false;' after the if statement, but then it won't proceed to new page when a list selection is made.
Thanks in advance for any assistance guys...

Okay, the comments above gave me part of the answer, but the complete solution was to change the first line of jquery if statement to:
if ($('#Button').attr('href') == '') {
So I needed to add the # before Button, but also change from === undefined to == ''
Just adding the # before Button without changing the second part killed the alert altogether. I was then also able to add return false; after the alert to prevent the page from reloading upon empty button click.

Related

.attr('checked', true)Will Not Re-add on button click

I have a form with a 'Reset' button. When i select my radio button the data from my DataTable is passed and pre-pops my fields. This working fine and does in fact pre-populate the relevant radio button
JQuery
if (modifyRecordData.startTime == 'Anytime') {
$('#anyTimeRadioButton').attr('checked', true);
$('#specificTimeRadioButton').removeAttr('checked');
$('#startEndTimeFields').hide();
} else {
$('#anyTimeRadioButton').removeAttr('checked');
$('#specificTimeRadioButton').attr('checked', true);
$('#startEndTimeFields').show();
$('#startTimeHr').val(modifyRecordData.startTimeHr);
$('#startTimeMin').val(modifyRecordData.startTimeMin);
$('#endTimeHr').val(modifyRecordData.endTimeHr);
$('#endTimeMin').val(modifyRecordData.endTimeMin);
}
Data returned
Page loaded
Now the issue, if the user, after data load goes to update the details and selects the other radio button the hidden fields are displayed (again correct)
Then user clicks the 'Reset' button and it fails in the correct function
$('#resetButton').mousedown(function (event) {
buttonclicked = "Reset";
event.stopImmediatePropagation();
modifyRadioButtonSelection(modifyRecordData);
})
and then goes back to the initial loaded data and it does drop in the IF code above
Debuging
Then it re-hides the hidden section (which is correct) but it does not re-tick the radio button as expected.
If i dont have the following code in the IF it leaves the previously selected one checked although the data falls in the IF
$('#specificTimeRadioButton').removeAttr('checked');
No idea whats going wrong at all. I even tried adding the following the 'Reset' button function but it just will not re-check the correct `radio button
$('#anyTimeRadioButton').removeAttr('checked');
$('#specificTimeRadioButton').removeAttr('checked');
Historically, there's been a lot of ambiguity and confusion between three related but different concepts:
The value of the HTML attribute in the source code.
The value of the HTML attribute in DOM tree.
The value of the JavaScript property.
To address that, jQuery/1.6.1 introduced the prop() method, which I suggest you adopt.

divs hide correctly on page load, but need to show when back button is clicked

I have several divs that are to be hidden on page load on a html form I am designing. Some contain text fields, some contain dropdown boxes. The are shown based on when certain radio buttons are clicked in the form. I am using javascript to hide the divs. Here is the code I am using:
<script language="JavaScript">
function start() {
hide('hideablearea');
hide('nontenant');
hide('conftype');
hide('rec_roomlayout');
hide('req_roomlabel');
hide('req_roomdrpdwn');
}
window.onload = start;
</script>
It works perfectly. My problem is...when the form is submitted and there is an error (for example, the user forgets to complete a required field) and clicks the back button, this function fires again and hides everything..and I want the hidden divs which have info inthem to show at this point. Any idea on how to achieve this?
Thanks in advance!
K
You might want to re-think your design if once you display an error message, the user needs to click Back to go to the previous page and correct the information. The previous page will have no concept of the error message. I can see two ways to correct this.
1) Do all error checking in JavaScript
If you implement your error handling in script, you can immediately inform users of errors and missing information before the page is submitted. You would then only submit the form if everything checks out.
2) Re-display the form on post back
When the user submits the form, you'd do required error checking on the server. You would then re-render the form again, with all the user-entered information, and display error messages. On this page, you'd write something like:
<script>var hasErrors = true;</script>
If the page has errors, your client side script could avoid hiding the relevant information. No-where in this model does the user need to click the Back button to correct their mistakes.
You can put id attribute to your divs and then control if your div has a message to show then you didn't hide them.
Like this:
<script type="text/javascript">
function start() {
if (document.getElementById('hideablearea') == "") {
hide('hideablearea');
}
...
}
</script>

jquery submit form once

I am trying to write a custom magento module and i've got it all complete and working perfectly except one problem.
The module is a form with 4 radio buttons. They are all blank on the checkout page and I have them set up so that when you click one it submits the form and reloads the cart page with the "additional fees" in the subtotal.
My problem is that I need the first option to "auto submit" on page load. But I've tried ALOT of different things and can't come up with a way to use the jquery .submit() function to ONLY submit the form once. as it is now it works how I want it, except it loads the page in an endless loop.
Any way to say submit() only once?
I'd set the default radio button server-side rather than having an extra submit/refresh cycle, but if you insist on doing it client-side...
I assume on subsequent refreshes the previous selection will be retained (because your server-side code echoes back the previously selected values?), so can you perhaps test whether any radios are checked and if not assume that that is the first and only time to auto-submit?
$(document).ready(function() {
var $radios = $('#yourFormId input[name="yourRadioButtonGroupName"]');
if (!$radios.is(":checked")) {
// No radios currently checked, so check the first and submit
$radios.eq(0).prop("checked",true);
$("#yourFormId").submit();
}
});
The .is() method will "Check the current matched set of elements against a selector, element, or jQuery object and return true if at least one of these elements matches the given arguments."

jquery, replace html on submit

I have a form which is using a select list to jump around my site. This is currently using onclick window.location so user selects the page and presses go and it goes to that page.
I now need to add a small text box for the user to type in a code (say 123456) and then when they click go, it should go to the url selected, but with the [CODE] being the number entered in the box. I discovered jquery replaceAll so it gave me the idea to have this in the select html:
http ://jumptothispage.com/parts/p[CODE]/edit
http ://jumptothispage.com/jobs/j[CODE]/edit
When you press go, it would replace all [CODE] in that html with the code entered and then jump to that page selected, e.g.
http ://jumptothispage.com/parts/p123456/edit
http ://jumptothispage.com/jobs/j123456/edit
I am already using jquery on my site so makes sense to try and utilize that again. I'd appreciate a pointer and or other suggestions instead.
Thanks,
Paul.
A workaround: Store the code in a cookie, so at least it's not visible to every person who looks at the URL bar. Then in every onclick, fit it into the URL to send the user to the "right" page.
Or, have your select option's value literally read CODE, which your onclick interprets to mean "The user hasn't set the code yet." When the user types in the code, store it in a variable (in the example below, realcode), and you can then do this:
$('select#navigation option').each(function(idx, el) {
$(el).attr('value', $(el).attr('value').replace(/CODE/, realcode));
});

How to prevent multiple html selection box displayed on screen?

I have been working on the last bit of my php + ajax based datagrid project.Everything works as I designed except one thing : I cannot stop user opening multiple selection boxes...
Go my research page and use username "ChenxiMao" and password "accedo" to login(without double quotes).
Note that perhaps the images used in this datagrid would not be displayed when page is loaded for the first time(weird, I am trying to fix this, browser incompatibilities, perhaps).
If you double click on one cell in the "CONSULTANT" column, a html select box would be displayed, you can select one consultant to assign him to this task or unassign the consultant from this task. No problem for this.
The problem is : when user leaves this selection box OPEN, he/she can still open another selection box... My jquery code cannot stop people from opening multiple selection boxes.
You can ctrl-U to see the source code on this page, and check the content inside the "gridview-helper.js" for what I have been done.
I want to let user only open a single selection box. When he/she leaves the cell, the selection box should be closed, without changing the html inside...
Puzzled, screwed up for this afternoon...
Thanks for any suggestons in advance!
JavaScript is single-threaded, so you can add a mutex variable and check its value before opening a new select box.
At the top of gridview-helper.js:
var is_choice_visible = false;
In your double-click handler:
$(this).dblclick(function()
{
if (is_choice_visible)
return;
is_choice_visible = true;
...
For your select box, add an onblur handler which sets is_choice_visible back to false and deletes itself.
Unrelated tip: Growing a string in a loop is slow on older versions of Internet Explorer. It's more efficient to append to an array and join the array, e.g.:
var html = ["<select>..."];
for (var i in consultantnames)
{
html.push("<option>...</option>");
}
html.push("</select>");
return html.join("");
Have you tried using the onmouseout event on the cell, and removing the child dropdown box element if mouse out is triggered? Seems that should work.

Categories