Simple javascript form reset when certain text boxes are clicked - javascript

Morning all...thicky, newbie Rich here!
I have a very simple set up, three different search options for finding product information i.e. a cascading drop down list, a product search text box and a radio button list.
Ideally, I do not want the form to get cluttered with information or have to use a 'click here to reset' button.
What I would like is for the form to reset/clear itself when a user either hits the drop down, the text box or the radio button list. Therefore this will ensure the searching does not get cluttered with information that potentially isn't being used.
How would one go about doing this? As per my other questions, please excuse my ignorance.

What you want to do is fairly simple with jquery if you're using it. Without knowing your exact markup I can really only pseudo-code it out for you, but something like this should be a start:
<script language="javascript" type="text/javascript">
$(document).ready(function() {
$inputs = $("#places, #search, #radio_search");
$.each($inputs, function() {
$(this).focus(function() {
$.each($inputs, function() {
$(this).val('');
$(this).attr('checked', false);
})
});
})
});
</script>
You want to inlcude the jquery library and add this to the head tag of the html page you want to do this on. You'll also need to make sure the $inputs = $("#places, #search, #radio_search"); matches the specific ids of the inputs you're trying to change.

Ok dokey, got it to work, lovely stuff.
However, in my drop down list, I wish to retain the orignal value rather than clear it all together, the current working code is as follows.
<script language="javascript" type="text/javascript">
$(document).ready(function() {
$inputs = $("#tbxProdAC, #ddlBuyer, #txtbxHowMany, radTopx");
$.each($inputs, function() {
$(this).focus(function() {
$.each($inputs, function() {
$(this).val('');
$(this).attr('checked', false);
})
});
})
});
Is there a way I can specify the individual values i.e. tbxProdAC ='',
ddlBuyer = Original Value, txtbxHowMany='', radTopx =''?

Related

How to Show/Hide Column Fields Based on Other Fields - SharePoint

I have a table with multiple columns in SharePoint and I am frequently adding new records into this table. The hard part of this, having a lot of columns make it difficult and causes confusing.
In below code, I hide all the columns and based on selection in the dropdown list, the fields will be shown to be key in. This test dropdown list consists of Country, Fruit, Animal and Colour it only gives me two option showing and hiding but I want to do same process for multiple fields. I am not sure how to do it. I will be grateful for your help, if you could direct me on how to do it.
Thanks
<script src="/SiteAssets/jquery-3.3.1.js"></script>
<script src="/SiteAssets/sputility.js "></script>
<script>
$(document).ready(function ()
{ // Get a the choice field
var choiceField = SPUtility.GetSPField('Selection');
// Hide the target fields in form load
SPUtility.HideSPField('Country');
SPUtility.HideSPField('Fruit');
SPUtility.HideSPField('Animal');
SPUtility.HideSPField('Colour');
// create a function to show or hide a field based on the selected choice Field value
var ShowHideField = function() {
var selectedFieldValue = choiceField.GetValue();
if (selectedFieldValue != 'Country') {
SPUtility.ShowSPField('Country');
SPUtility.ShowSPField('Animal');}
else if (selectedFieldValue != 'Fruit') {
SPUtility.ShowSPField('Fruit');
SPUtility.ShowSPField('Country');
SPUtility.ShowSPField('Animal');}
};
$(choiceField.Dropdown).on ('change', ShowHideField); });
</script>
#LZ_MSFT thank you for your help and I am sorry for misleading you.
I actually wanted to show the multiple fields based on particular selection in the dropdown list.
Let's say, as shown in the script above, when I choose country in the dropdown list both country and animal fields should appear or when I choose Fruit in dropdown list fruit, country and animal fields should appear. In above script, it works perfectly. However, I want to apply same process for more than 2 cases. Like, I want to choose Color and display only animal and fruit but I am not sure how to apply it after using If else statement.
If you could show me, I would be grateful for your help.
Thank you
The following code for your reference:
<script src="//code.jquery.com/jquery-1.12.4.js" type="text/javascript"></script>
<script type="text/javascript">
$(function(){
var fields=["Country","Fruit","Animal","Colour"];
hideFields(fields);
$("select[title='Selection']").change(function(){
$(".ms-standardheader nobr:contains('"+$(this).val()+"')").closest("tr").show();
});
});
function hideFields(fields){
for(var i=0;i<fields.length;i++){
$(".ms-standardheader nobr:contains('"+fields[i]+"')").closest("tr").hide();
}
}
</script>
If the code not meet your requirement, I suggest you provide more information for further research.

Html select not changes option on click after jquery instant filter in jsp

I have 3 select tags on one page, generated from struts2 select tag. I am using a jQuery filter function that filters the select. One textfield for every select, but all of them use the same filter function. I have another js function that is called on onChange event.
The problem is that before adding this jQuery function i was filtering the lists with form submit and reload the page and now the filtration happens instant, but when i write a filtration criteria the select somehow the select loses focus and when i click an element no select happens, or better lets say is a kind of select: the element is circled with a dotted line, not selected with a blue filled square. The js is called, the form submitted, but with the old value. However, if i first click in the select where are no elements (empty zone) and then i select an element everything is ok. How can i jump over the firs click?
And now my code:
I. The jQuery filter function and the binding to the selects and textfields.
jQuery.fn.filterByText = function(textbox) {
return this.each(function() {
var select = this;
var options = [];
$(select).find('option').each(function() {
options.push({value: $(this).val(), text: $(this).text()});
});
$(select).data('options', options);
$(textbox).bind('change keyup', function() {
var options = $(select).empty().scrollTop(0).data('options');
var search = $.trim($(this).val());
var regex = new RegExp(search,'gi');
$.each(options, function(i) {
var option = options[i];
if(option.text.match(regex) !== null) {
$(select).append($('<option>').text(option.text).val(option.value));
}
});
});
});
};
$(function() {
$('#selectedClientId').filterByText($('#filterClient'));
$('#selectedLocationId').filterByText($('#filterLocation'));
$('#selectedViewPointId').filterByText($('#filterViewpoint'));
});
II. One of the selects:
<s:select size="10" cssStyle="width:220px;"
label="Select a client"
listKey="id" listValue="name"
list="clientSelectList"
name="selectedClientId" id="selectedClientId"
headerKey="-1" headerValue="Client List"
onchange="onChangeSelect()"
/>
III. The select's textfield:
Filter:<s:textfield name="filterClient" id="filterClient" size="15" autocomplete="off"/>
IV. The onChangeSelect():
function onChangeSelect() {
document.getElementById('deviceListForm').action = '<s:url value="/admin/displayDeviceListPage.action"/>';
document.getElementById('deviceListForm').submit();
}
In the image: in the first select is how looks the selected option after jquery filter and in the other 2 selects are "the good" selected options.
http://i.stack.imgur.com/TAJeY.png
EDIT: So, after the first response to this post (Thanks Amit1992) I started digging further. In Mozilla after the first click (after the frame or dotted line appears) a request is made to the server with the old selected item (or null if none selected), the page refreshes as nothing happened.
In Chrome, on the other hand, the first click does not make any request. It just selects (let's say) the select tag. And the second select makes a good request.
Short story:
mozilla: click 1 -> request with old selected value ->refresh -> no changes
chrome: click 1 -> selects the select tag and no request is made -> click 2 -> request as it should happen
IE - works ok. 1 click-> select and load page as it should . OK this really surprises me. at first I thought is useless to look in IE what happens.
EDIT2
After some digging i concluded that the problem is that when typing in the textfield the select loses focus. If I put $('#selectedClientId').focus();
in the filterByText function at the end of the $(textbox).bind('change keyup', function() the fist select is focused after every char written. But this gives me another problem. I can't write more than 1 char at a time. I have to click the textfield, write a char, click again, write a char etc.
May be this will help you. i did some modification in your code.
$(function() {
$('#selectedClientId').filterByText($('#textbox'), false);
$("#selectedClientId").change(function(){
alert("you have selected ++ " + $(this).val());
});
});
I used change() event of jquery instead of javascript onChange().
you can refer this link http://jsfiddle.net/amitv1093/q55k97yc/ and I recommend you to use jquery fully if you are using it.
kindly let me know if it will work.
I solved the problem by changing the whole filter function. The function with problem was taken from a stack overflow question response (How to dynamic filter options of <select > with jQuery?). The problem is, from what I concluded, that the $(textbox).bind('change keyup', function() line was changing the focus on the textfield, so the first click was changing the focus to the select tag. The new function, the one that works was taken from the same post, John Magnolia's answer:
$(document).ready(function() {
filterClient();
filterLocation(); //same as filterClient
filterViewpoint(); //same as filterClient
});
function filterClient(){
var $this, filter,
$input = $('#filterClient'),
$options = $('#selectedClientId').find('option');
$input.keyup(function(){
filter = $(this).val();
$options.each(function(){
$this = $(this);
$this.removeAttr('selected');
if ($this.text().toLowerCase().indexOf(filter.toLowerCase()) != -1) {
$this.show();
} else {
$this.hide();
}
});
});
}

Using JavaScript or JQuery to automatically check asp:checkbox when a button is pressed

I have a feature that allows the user to search the database for an item that matches the string they type in. For example, if they type in "Superman" it'll return whatever is in the database that is associated with Superman. Next to each item in the resulting list is a checkbox. If the user selects a checkbox, they can then press the "delete" button to remove that item from their list. I want to be able to select all of the checkboxes by pressing a "select all" button. Sometimes the lists are really long and if the user wants to delete all of the items, it would be time consuming to select and delete each one individually.
The checkbox is an asp:checkbox inside of an asp:TemplateField. The asp:TemplateField is inside an asp:GridView. Here is the checkbox code:
<asp:TemplateField HeaderText="Select">
<ItemTemplate>
<asp:CheckBox ID="uxSelectAdd" runat="server" />
</ItemTemplate>
For the "select all" button, I'm using a regular input type:
<input type="submit" value="Select All" id="uxSelectAll" />
Here are the contents of the js file I'm using in my resources folder(I'm using the alert function for debugging. For some reason, the alert pops up when the page loads, rather than when I click on the button. Clicking the button doesn't do anything):
$(document).ready(function () {
$('#uxSelectAll').click(function (e) {
$(searchCheckBoxSelector).prop('checked', true);
alert("helloooo");
});
});
This is the js that is included in the front-end code at the top inside of a script tag:
<script type="text/javascript">
var searchCheckBoxSelector = '#<%=uxSearchedComics.ClientID%> input[id*="uxSelectAdd"]:checkbox';
</script>
I know that .live is no good since it's been removed in the version of javascript that we're now using, so I tried changing .live to .click instead. That didn't work. I also tried adding this js to the front-end instead of what was already there, just to experiment and see if this works:
<script type="text/javascript">
$(document).ready(function () {
$('#uxSelectAll').click(function () {
alert('hello world');
});
});
</script>
For some reason, that didn't work either. Am I missing something obvious? I wanted to at least get an alert to work before I tried adding in code to check all of the checkboxes for me but not even the alert works. I'd appreciate any help or nudges in the right direction.
Here are the .js files I'm using in the front-end code:
<script src="../../../../resources/js/ItemSlotEdit.js" type="text/javascript"></script>
<script src="../../../../resources/js/plugins/jquery-1.11.0.js" type="text/javascript"></script>
I want to share the solution I'm using. I've kept the input element exactly the same and this solution is in a separate js file that I've included into the .aspx front-end file.
$(document).ready(function () {
$('#body').on('click', 'input[type=submit]#uxSelectAll', function () {
$(this).toggleClass("checked");
var isChecked = $(this).hasClass("checked");
$('input[type=submit]#uxSelectAll').val(isChecked ? "Unselect All" : "Select All");
$(this).prev().find(":checkbox").prop("checked", isChecked);
return false;
});
});
The reason the button wasn't working before is because the button was in a div that doesn't exist when the page loads. The div appears after the user clicks the search button and the search results come in. The search results are populated into a div that appears dynamically. So, in order to access the button you need to include a parent container in the selector. Otherwise the event delegation doesn't go through. I used the #body container because I have only a single Select All button and a single checkbox so it doesn't conflict with anything. The toggleClass function alternates between giving and removing the "checked" class on each click, and you can modify the text of an input element by using the .val property.
I hope this helps someone.

Radio button REQUIRED if input field has content

I have a a reasonably quick problem to solve (I think). I have a form online and it validates the required content for the user's data, but has no validation on the first part of the form.
I've been asked however if I can make a radio button REQUIRED depending on whether an input field has been filled in.
The form can be found here:
http://www.elcorteingles.pt/reservas/livros_escolares/form.asp
So if the person start's filling in the input fields on the first line, that the radio buttons in the group become REQUIRED (for either the CDROM ou CADERNO but not both)
You can handle the focusout and blur events for the input:
$(function () {
// Handle every input type text.
// To select specific inputs, give them a common class and change the
// selector accordingly.
$("input[type=text]").on("focusout blur", function () {
// Check for inputs with class radio_btns which are in
// the parent element (li).
// Set their required property.
$(this).parent().find("input.radio_btns")
.prop("required", $(this).val().trim().length > 0);
});
});
Demo
jQuery reference (Tree Traversal)
jQuery reference (.prop())
jQuery reference (.focusout())
jQuery reference (.blur())
This will work. You can include the following JQuery code in the script tag, and also the JQuery cdn link in the head tag.
$(document).ready(function(){
$('#01titulo').focusout(function(){
if ($(this).val() !== "") {
$('[name="01caderno"]').prop('required', true);
} else {
$('[name="01caderno"]').prop('required', false);
}
alert($('[name="01caderno"]').attr('required'));
});
});
Try using the following js code its working:
$(document).ready(function(){
$(".titulo_books").each(function(){
$(this).focus(function(){
var radioChecked=0;
var currElemId = parseInt($(this).attr('id'));
var radioSelecterId = (currElemId>9) ? currElemId : "0"+currElemId;
$("input:radio[name="+radioSelecterId+"caderno]").each(function(){
if(radioChecked==0)
{
radioChecked==1;
$(this).attr("checked","checked");
}
});
});
});
});
I have checked it by executing this from console on your site and it seems to work fine. You can alter this in the way you want. I have checked one of the four available radio button. User can change the input value if required. Or you can also change the default radio button selected through my code.

jQuery UI multiple selections

see this demo from jquery ui
you have to hold down the Ctrl key to make multiple selections
I really like the code but I don't want to force my visitor to press ctrl key
I want the code to allow multiple selections without holding ctrl key
is this possible?
I asked you a questions in the comments but I'll just write up a simple selection solution so you can see what I was thinking.
So basically you can use the jquery toggle() effect to roll your own selector. When a user clicks you'll add the orange class, when he clicks again it will remove the orange class.
$(document).ready( function() {
$('ul#selectable li').toggle( function() {
$(this).addClass('orange'); }, function() {
$(this).removeClass('orange'); } );
});
Then all your job is to grab all the li elements with the orange class and post them to a form or whatever your end goal is. Haven't checked this code but what your doing is asking for all the li elements within selectable that have the orange value at the end of the class attribute.
With the code below I'm creating a new array and then adding the text() value of each "orange li" into it.
var theSelections = new Array();
$('ul#selectable li[class$="orange"]').each( function(i) {
theSelections[i] = $(this).text();
});
Yes. However, the implementation would have to allow selected items to be deselected when clicked on a second time. You would just need to modify the code slightly to achieve this.
Do a .selectable( 'Enable' ) on all the items.
Then you will need to do a .selectable( 'toggle' ) onClick on all items.
That should do the trick.

Categories