JQuery. Simple drop down selection menu behavior question - javascript

I have a simple html option/select (dropdown) menu. I want to use JQuery to redirect links when an option is selected. I have a "go" button in noscript tags in case javascript is disabled, but in the case that the user has javascript..I would like the redirection to happen automatically on-click. Could somebody please guide me on how to accomplish this using jquery (I have this done using simple javascript 'onclick' events but I'd like to move all of my code to jquery)?
Right now my code looks like this (the function gets call from the 'onclick' event):
function option(dropdown) {
var myindex = dropdown.selectedIndex
var SelValue = dropdown.options[myindex].value
var baseURL;
if(SelValue=="1")
baseURL="something1";
else if(SelValue=="2")
baseURL="something2";
else if(SelValue=="3")
baseURL="something3";
top.location.href = baseURL;
return true;
}

To bind the click element in jQuery you can do
$('#elementId').click(function(){
//do redirection
});
But for you case I think you need to bind the change event
$('#elementId').change(function(){
var optionSelectedValue = $('#elementId option:selected').val();
if(optionSelectValue == value1) {
newUrl = url1;
}
else if(optionSelectValue == value2) {
newUrl = url2;
}
top.location.href = newUrl;
});

Related

Prefill checkbox via link and preserve form function

I currently have a form i built that is 3 large check boxes, when selected they toggle the continue button below them, https://staging-homecarepulse.kinsta.cloud/demo-select/ this is the link so you can check it out.
Currently im trying to add functionality to the form that when you click a link from another page, it preselects the checkbox depending on the link selected.
I was able to find a script that allows me to setup a link with a hash ( https://staging-homecarepulse.kinsta.cloud/demo-select/#checkbox1 ) but my issue is that I cannot get the continue button to trigger when the form is accessed this way.
here is my code
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
var hash = location.hash;
if(hash=="#checkbox1"){
$("#checkbox1").prop("checked", !$("#checkbox1").prop("checked") ); // that toggles the checked state
}
});
</script>
<script>
$(document).on("change", ".mod-link", function() {
var arr = []
$(".mod-link:checked").each(function() {
arr.push($(this).val());
})
if (arr.length > 0) {
$('#picture').attr('src', '');
} else {
$('#picture').attr('src', 'https://staging-homecarepulse.kinsta.cloud/wp-content/uploads/2021/06/greyBTN.jpg');
}
var vals = arr.join(",")
var str = "/demo/?demo_request_type=" + vals;
var link = arr.length > 0 ? '<a class="dynabtn" href="'+str+'">Continue</a>': '' ;
$('.link-container').html(link);
});
</script>
anyone have any idea how i can use links like https://staging-homecarepulse.kinsta.cloud/demo-select/#checkbox1 to trigger that checkbox and still have the continue button toggle on?
Instead of trying to toggle the checked property, fire a click event on your checkbox.
$(document).ready(function() {
if (location.hash) {
let $checkbox = $(location.hash);
if ($checkbox.length) $checkbox.click();
}
});
Your Continue button will toggle as well.

How can I exclude a button and a label from form serialization?

I want to use form serialization but exclude a button and a label from the serialization.
This is a version of the javascript I have:
var saveBtn = document.getElementById("btnSaveButton");
var saveLbl = document.getElementById("lblSaveLabel");
var originalFormData = $("#MasterForm").not(saveBtn, saveLbl).serialize();
$("form :input").on('change keyup paste mouseup', function () {
var newFormData = $("#MasterForm").serialize();
if (originalFormData != newFormData) {
//some code
} else {
//some other code
}
});
See: .not(saveBtn, saveLbl)
That is not excluding the button or the label.
Can someone please help me and let me know how I can exclude the button and the label from the serialization?
What essentially happens is I switch the display from the button to the label and back depending on whether the user has made any change to the form.
UPDATE UPDATE
Thank you for the responses ... appears something is amiss ...
There might be too much html to post here ...
Using vb.net. I have a master page, within it is a page called Admin.aspx, and within that is a usercontrol called Bundles.ascx.
In the code of Bundles.ascx I have this javascript:
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_pageLoaded(prmRequest);
prm.add_endRequest(prmRequest);
function prmRequest(sender, args) {
setupFormChangeCheck("btnSaveBundle", langId);
}
In a master javascript file I have the function setupFormChangeCheck, which looks like this:
function setupFormChangeCheck(txtName, langId) {
try {
savebtnFnctn('dis', txtName, langId)
var originalFormData = $("#MasterForm").serialize();
$("form :input").on('change keyup paste mouseup', function () {
var newFormData = $("#MasterForm").serialize();
if (originalFormData != newFormData) {
savebtnFnctn('en', txtName, langId)
} else {
savebtnFnctn('dis', txtName, langId)
}
});
} catch (err) { }
}
On the same master javascript file I have the function savebtnFunction, which looks like this:
function savebtnFnctn(event, txtName, langId) {
var saveBtn = document.getElementById(txtName);
var saveLbl = document.getElementById(txtName.replace("btn", "lbl"));
if (event == 'en') {
saveBtn.style.display = "inline";
saveLbl.style.display = "none";
} else if (event == 'dis') {
saveBtn.style.display = "none";
saveLbl.style.display = "inline";
}
}
The user control is loaded dynamically, because the same page has multiple use controls and unless I load the one control dynamically, all load ... slows things down incredibly.
Loading a user control dynamically leads to serious postback challenges. So, the vast majority of the user control interactions are handled client side with jquery. For Bundle.ascx this is done in Bundle.js
SOOOOO ....
When the user control is loaded, setupFormChangeCheck fires, which runs the 'dis' (disable) event in function savebtnFnctn.
Here is the problem I noticed today as I tried the code from suggestions above.
When I interact in the Bundle uc, setupFormChangeCheck does not fire from the beginning. What first fires is this line $("form :input").on('change keyup paste mouseup', function ()
And no matter what I do, click in a textbox even without changing anything, leads this: originalFormData != newFormData to be true and the Save button remains enabled ...
I should add that all the controls in the Bundle user control are inside an updatepanel:
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
Long explanation I know, sorry ... if anyone has any idea to solve this, I would be eternally grateful.
Thank you. Erik
The jQuery's .not() method takes selector, not elements.
Also, you are matching the form itself, not the inputs of it.
Since you do know the IDs of the elements to exclude, use this instead:
var data = $("#MasterForm").find("input, textarea, select").not("#btnSaveButton, #lblSaveLabel").serialize();
You select the form.
Then you select the form elements underneath.
Then you exclude the concrete elements from the collection.
Lastly you serialize the results.
NOTE: You should use strict comparison !== instead of !=.

Jquery, onBlur - if not empty show an alert

I'm trying to modify some other code that I found on SO, but it's not working (I'm still learning JQ)
My code:
$("#Email").blur(function(){
var inp = $("#Email").val();
if(jQuery.trim(inp).length > 0)
{
alert("Yay!");
}
} );
Basically (in case it's not clear) I want to fire that alert() as the user moves away from the textbox - only if the user entered something in the textbox.
Code seems to work, make sure the field is loaded before binding the event, preferably using $(document).ready()
$(document).ready(function(){
$("#Email").blur(function(){
var inp = $("#Email").val();
if(jQuery.trim(inp).length > 0)
{
alert("Yay!");
}
} );
})
Here is the related fiddle

Determining which submit button was clicked from jQuery/JavaScript [duplicate]

This question already has answers here:
How can I get the button that caused the submit from the form submit event?
(22 answers)
Closed 9 years ago.
I'm ajaxifying some forms from a PHP application I didn't write. To do this, I came up with this clever solution:
jQuery("form").submit(function(event) {
// get some values from elements on the page:
var the_form = jQuery(this);
var data = the_form.serialize();
var url = the_form.attr( 'action' );
var button = event.originalEvent.explicitOriginalTarget;
data = data + "&" + button.name + "=" + button.value;
// Send the data using post and put the results in a div
jQuery.post( url, data, function() {
//Do something crazy
});
// stop form from submitting normally
if (event.preventDefault)
{
event.preventDefault();
}
else
{
event.returnValue = false;
}
});
Which works perfectly. I went away rejoicing. The problem is, I inadvertently used a Mozilla/Gecko only property to determine which button was clicked. (event.originalEvent.explicitOriginalTarget) Which means this only works in Firefox. :-(
All of this is necessary because the web app I'm augmenting relies on the button name/value being in the post data to process the form correctly. So, my question in simple terms would be:
What is the best, cross-browser way to determine which button was clicked in jQuery's submit event?
Edit:
And here is my solution.
jQuery("some selector that targets your form").find(":submit").click(function(event) {
// get some values from elements on the page:
var the_form = jQuery(this).parents("form");
var data = the_form.serialize();
var url = the_form.attr( 'action' );
var button = event.target;
data = data + "&" + button.name + "=" + button.value;
// Send the data using post and put the results in a div
jQuery.post( url, data, function() {
//Do something crazy
});
// stop form from submitting normally
if (event.preventDefault)
{
event.preventDefault();
}
else
{
event.returnValue = false;
}
});
See this question: Crossbrowser equivalent of explicitOriginalTarget event parameter
You're going to have to attach the event listeners to the buttons instead of the form to get a good reliable way of determining which one fired the submit.
http://api.jquery.com/event.target/
jquery.event.target should work because it is normalised for most browsers.
jquery.event.currentTarget can be used to retrieve the current item in the event bubbling chain.
Edit--
After some reflection and #greg's suggestion:
I've posted a code snippet on jsfiddle.
Using click handlers to submit the form is problematic beacuse you cannot use submit event handlers for validation (which is the way pretty much any validator plugin does it). Also, when you are not using AJAX to post, disabling submit buttons can have weird effects in some browsers if done in the click event and not the submit event.
The way jQuery.Form solves this is to set up a click handler which stores the clicked button (and then clears it with a small timeout), and use the submit handler to actually send the form contents via AJAX.
Here is a function I used to "ajaxify" my forms with jQuery.
function ajaxifyForm(form, callback)
{
var clicked
form.find("button").click(function()
{
if (clicked != null) clicked.removeAttr("data-clicked")
clicked = $(this)
$(this).attr("data-clicked", 1)
})
form.submit(function(event)
{
var data = {}
var name = ""
form.find(":input").each(function()
{
var input = $(this)
if (!(name = input.attr("name"))) return
switch (input.attr("type"))
{
case "radio":
case "checkbox":
if (input.attr("checked")) data[name] = input.val()
break
case "submit":
if (input.attr("data-clicked")) data[name] = input.val()
break
default:
data[name] = input.val()
}
})
$.ajax({
url: form.attr("action"),
success: function(data)
{
if (typeof callback == "function") callback("success")
},
error: function()
{
if (typeof callback == "function") callback("error")
},
data: data,
type: form.attr("method")
})
return false
})
return form
}

Tab panel problem

How can I get selected tab index of tab panel using JavaScript and then assign a button validation group according to selected tab index?
This is my code so far:
function ActiveTab()
{
var a= $find("tcEmployee").get_activeTabIndex();
var add=document.setElementById('<%=btnAddRecord.ClientID%>');
var update=document.getElementById('<%= btnUpdateRecord.ClientID%>');
var delet document.getElementById('<%= btnDeleteRecord.ClientID%>');
if (a == 0)
{
add.ValidationGroup = "Insertion";
update.ValidationGroup = "Insertion";
delet.ValidationGroup = "Insertion";
}
else if (a == 1)
{
add.ValidationGroup = "Insertion1";
update.ValidationGroup = "Insertion1";
delet.ValidationGroup = "Insertion1";
}
else
{
add.ValidationGroup = "Insertion2";
update.ValidationGroup = "Insertion2";
delet.ValidationGroup = "Insertion2";
}
}
You can try with Jquery tab.
Have you considered using a click event on the tab?
Maybe look at the jQueryUI tab control and get the event that way.
Also, try including more information in your question so we can actually target our answers to an actual problem
edit
OK, looking at your code i think jQuery is going to be your friend.
if you give each of your controls an ID like you are doing and also a class. So for the "add" alement you may give it a class of "ADD" and for"update" a class of "UPDATE".
Then you can use jQuery like this;
$(".UPDATE").click(function(){
alert( $(this).attr("id") );
})
$(".ADD").click(function(){
alert( $(this).attr("id") );
})
etc....

Categories