jQuery Trigger onKeyup Event - html

I have a SELECT LIST MENU containing products and on this menu i use onChangeevent. when you select any product, it load company name of that product.Below is the function which i used,
function getcompany(element) {
var strURL="getcompany.php?product="+element.value;
var req = getXMLHTTP();
if (req) {
req.onreadystatechange = function() {
if (req.readyState == 4) {
// only if "OK"
if (req.status == 200) {
element.parentNode.parentNode.getElementsByClassName('companydiv')[0].innerHTML=req.responseText;
} else {
alert("There was a problem while using XMLHTTP:\n" + req.statusText);
}
}
}
req.open("GET", strURL, true);
req.send(null);
}
}
And my html code is,
<select name="product" onChange="getcompany(this)">
<option value="1" >Product1</option>
<option value="2" >Product2</option>
</select>
<div class="companydiv">Product result will be shown here</div>
The above code work but now i want to use jquery autocomplete instead of SELECT LIST MENU because my product list containing more then 1000 products.
My Autocomplete code is,but i dont know where i'm wrong
<input name="product" id="product" type="text" onkeyup="getcompany(this)" />
Some other answers i already checked but i'm not satisfied with anyone, some of them are below
jQuery AutoComplete Trigger Change Event
Jquery Autocomplete onChange event
http://forum.jquery.com/topic/autocomplete-and-change-event

I could not find your error here, however I could make what you are trying to do. I used jquery here. jsFiddle

Related

disabling the data from dropdown when same data we typed in input field with jquery

How can I write a jQuery function that disables the value from dropdown only if same data we typed in input field.
Input Field - NEW
So from drop down new should be disabled.
<select class="form-control" id="select2">
<option value="1">New</option>
<option value="2">OLD</option>
</select>
You can do it like this:
$('.typeVal').on("keyup change",function() {
var $val = $(this).val();
$('#select2 option').prop("disabled", function() {
return $(this).text() == $val;
});
});
This code is using jQuery to bind an event handler to elements with the class .typeVal. The event handler will be triggered on "keyup" and "change" events on these elements.
When the event is triggered, the code gets the value of the element that triggered the event and stores it in a variable $val. Then, it sets the "disabled" property of all the elements within the #select2 element based on a function.
The function returns true if the text content of the element is equal to $val, meaning it will disable the if it has the same text content as the triggering element. If the text content of the is not equal to $val, the function returns false and the will not be disabled.
Demo
$('.typeVal').on("keyup change",function() {
var $val = $(this).val();
$('#select2 option').prop("disabled", function() {
return $(this).text() == $val;
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input class="typeVal" />
<select class="form-control" id="select2">
<option value="1">New</option>
<option value="2">OLD</option>
</select>

How to stop refreshing the select box option after pressing OK button

I have created a UI Page in Servicenow below is my simple HTML snipped that creates a Select box and a OK button
Now i selected the select box as Mango and i typed ok, once i click on ok it is setting the value but when i refresh the browser it going to back to previous view. how to keep the same option which user select until user changes it
function validation(){
var value=document.getElementById("selectedValue").value;
if(value=='disabled selected')
{
alert("Please select any value before submitting");
}
else if(value=="1"){
alert("hello this is mango");
}
}
<div class="container">
<div class="row">
<div class="form-group" style="margin-top:12px;">
<select class="form-control" name="selectedValue" id="selectedValue" style="width:150px;">
<option value="disabled selected">Choose your option</option>
<option value="1" >Mango</option>
<option value="2">Orange</option>
<option value="3">Grapes</option>
</select>
<!--<h4 id="number_of_updates" style="display:none"><span class="label label-danger"></span></h4> -->
</div>
<button type="button" class="btn btn-primary" onclick="validation()" style="padding: 0px 8px;">Ok</button>
</div>
</div>
It is working as required, when i refresh the browser it will be set to Choose your option. Can anyone please help me how to save the selected value till it is changed
To achieve the desired result I would use localStorage.
I would set localStorage item inside your validation() function:
function validation(){
var value=document.getElementById("selectedValue").value;
localStorage.setItem('MyValue', value);
if(value=='disabled selected')
{
alert("Please select any value before submitting");
}
else if(value=="1"){
alert("hello this is mango");
}
}
Note, that I'm setting it to selected value from selectList.
Then we need to retrieve this saved value on page load(in case someone refreshes the page):
window.onload = function (){ //function that is called when your page
var selectList = document.getElementById('selectedValue');
var stored = localStorage.getItem('MyValue');
console.log(stored);
if(stored && selectList){
selectList.value = stored //setting saved value to as selected in selectList
}
}
EDIT: Even though localStorage is supported by majority of browsers, its is recommended to check if its accessible. Like if (typeof localStorage !== 'undefined') ...
There's several ways to keep state across refresh. localStorage is obvious choice but maybe an easier solution for your case may be encoding the state in the URL like this (basically the same way web apps keep some of their state).
Insert this code at the end inside validation() function:
history.pushState(null, '', '?val=' + value);
Insert this code after that function:
window.onload = function() {
var params = new URLSearchParams(location.search);
var value = params.get('val') || 'disabled selected';
var select = document.getElementById('selectedValue');
if (select) select.value = value;
}
That's it. Notes: URLSearchParams doesn't work on IE, instead it's not hard to parse the query by hand.

HTML Form: Other input required ONLY if other is selected

I'm currently working on a form with a bunch of options. On some of the questions, there is an "Other" option for the user to type in whatever they choose. I am trying to make it appear only "Other" is selected (I've gotten this to work on the first question but not the others). I am also trying to make this input required ONLY if they select it, so that they can't submit the form having selected "Other" and left it blank.
Here is my HTML and the Javascript for making the other text inputs appear when selected:
<label for="Accom">Question</label>
<table>
<tr>
<td><select name="Accom">
<option value="">Select...</option>
<option value="Handicapped">Handicap Accessibility</option>
<option value="Hearing Impaired">Hearing Impaired</option>
<option value="Visually Impaired">Visually Impaired</option>
<option value="OtherAccom">Other</option>
</select>
</td>
</tr>
<tr>
<td colspan="4">
<label style="" id="other">If Other, Please Specify
<input type="text" name="Other_Accom" size="20"></label></td><tr></table>
.
window.onload=function() {
var other = document.getElementById('other', 'otherAccom','otherDiet');;
other.style.display = 'none';
document.getElementsByName('Title', 'Diet', 'Accom')[0].onchange = function() {other.style.display =(this.value=='Other')? '' : 'none'};
I'm also trying to get a this to work for a checkbox form.
<label for="Interests">Question</label><br>
<input class="checkbox2" TYPE="checkbox" NAME="formInterests[]" required value="Use Cases ||" />Use Cases<br>
<input class="checkbox2" TYPE="checkbox" NAME="formInterests[]" required value="Other" />Other<br>
<label style="" id="other">If Other, Please Specify
<input type="text" name="Other_Interests" size="20"></label>
Thank you very much!
EDIT 1: When I try and duplicate the function, it stops working for everything.
window.onload=function() {
var other = document.getElementById('other', 'otherAccom', 'otherDiet');;
other.style.display = 'none';
document.getElementsByName('Title')[0].onchange = function() {other.style.display = (this.value=='Other')? '' : 'none'};
};
window.onload=function() {
var otherDiet = document.getElementById('other', 'otherAccom', 'otherDiet');;
otherDiet.style.display = 'none';
document.getElementsByName('Diet')[0].onchange = function() {otherDiet.style.display = (this.value=='OtherDiet')? '' : 'none'};
};
document.getElementsByName('Title', 'Diet', 'Accom')[0].onchange = function() {other.style.display =(this.value=='Other')? '' : 'none'};
This selects an array of elements, which you then access by [0], meaning you target the first element (which will be the first of the three that appears in the DOM), and add the onChange listener to it.
This results, as you said yourself:
(I've gotten this to work on the first question but not the others)
Because you actually only run the code on one of the three elements.
You should instead use something like:
document.getElementsByName('Title', 'Diet', 'Accom').forEach(function(element) {
element.onChange = function() {
var target = document.getElementById('Other'+this.name);
if(this.options[this.selectedIndex].value=='Other') {
target.style.display = 'block';
} else {
target.style.display = 'none';
}
};
});
The basic idea is using a forEach to loop through ALL your desired elements, rather than just one of them.
Keep in mind that:
<option value="OtherAccom">Other</option>
does not have value="Other", but value="OtherAccom". Make sure your javascript and html are consistent with eachother.
you can use IDs only once on a page ("other")
you need to rename those other "others" and create seperate functions for them

retrieving value of dynamically built set of checkboxes

I have a set of dynamically built checkboxes (sub-categories of main-category).
<input type="checkbox" name="SubCats" class="subcat-checkbox" value="18001700">first</input>
<input type="checkbox" name="SubCats" class="subcat-checkbox" value="18001800">second</input>
<input type="checkbox" name="SubCats" class="subcat-checkbox" value="18001900">third</input>
<input type="checkbox" name="SubCats" class="subcat-checkbox" value="18002000">forth</input>
Now when I submit the form, when I return back to the form from Server (if didn't pass validation, for example) I would like to be able to reconstruct that list of checkboxes with their values. Assume that the first two checkboxes were checked by the user I would like to have something like this:
<input type="checkbox" name="SubCats" class="subcat-checkbox" value="18001700" checked>first</input>
<input type="checkbox" name="SubCats" class="subcat-checkbox" value="18001800" checked>second</input>
<input type="checkbox" name="SubCats" class="subcat-checkbox" value="18001900">third</input>
<input type="checkbox" name="SubCats" class="subcat-checkbox" value="18002000">forth</input>
I assume that I do that as one of the first things here:
(document).ready(function () {
loadSubCategories();
}
I am using ASP.NET MVC and I can't figure out how do I deliver that information into the View (the HTML). I assume this is a common task in web development. How is it done in general?
You can use the localStorage provided by the web browser to store javascript variables to save the states of the checkbox and restore the states when teh webpage is loaded again.
This is how I did it:
function save() {
var elems = document.getElementsByName("SubCats");
var states = [];
for (i = 0; i < elems.length; i++) {
states.push(elems[i].checked);
}
localStorage.setItem("checkboxStates", JSON.stringify(states));
}
function restore() {
if (localStorage.getItem("checkboxStates") !== null) {
var states = JSON.parse(localStorage.getItem("checkboxStates"));
var elems = document.getElementsByName("SubCats");
for (i = 0; i < elems.length; i++) {
elems[i].checked = states[i];
}
}
}
restore();
Here is the JSFiddle demo
In the demo, you can check any checkbox you like and click the Save states button. When you re run the code, you will see that it keeps the previous settings.
The flow:
When you click the Save states button, the save() function is called and it builds an array of the checkbox states sequentially and serializes them before storing them in the localStorage.
When the page is loaded again, the restore() function is triggered by default. This checks if there are states saved before. And if there are, it deserializes then and then loops through the available checkboxes, setting the states back as previously saved.
Also note that the info stored in the localStorage can be accessed on any page and therefore the data is always available.
You can also read about sessionStorage.
Thank you all for all the help. These are all interesting suggestions, especially the one using localStorage which I have never used and perhaps I should give it a look.
Anyway, I decided to go for the naive way. I am keeping the checked Sub-Categories in a hidden text field separated by commas and then when building the tag again I am checking for every Sub-Category whether it has been checked before.
Here is my code:
function loadSubCategories() {
if ($("#ddlCategory").val() != "-1") {
var SubCatsCheckboxes = {};
SubCatsCheckboxes.url = "/BLHelpers/GetSubCats";
SubCatsCheckboxes.type = "POST";
SubCatsCheckboxes.data = JSON.stringify({ CategoryId: $("#ddlCategory").val() });
SubCatsCheckboxes.datatype = "json";
SubCatsCheckboxes.contentType = "application/json";
SubCatsCheckboxes.success = function (SubCatsList) {
var sub_cats = $("#SubCatsStr").val().split(",");
$("#SubCatsDiv").empty();
$.each(SubCatsList, function (index, value) {
var option_to_append = "<input type=\"checkbox\" name=\"SubCats\" class=\"subcat-checkbox\" value=\"" + value.SubCategoryId + "\"";
if ($.inArray(value.SubCategoryId.toString(), sub_cats) != -1) {
option_to_append += " checked "
}
option_to_append += ">" + value.Caption + "</option><br/>";
$("#SubCatsDiv").append(option_to_append);
});
};
$.ajax(SubCatsCheckboxes);
}
else {
$("#SubCatsDiv").empty();
}
}
Where :
<input id="SubCatsStr" name="SubCatsStr" type="hidden" value="#Model.SubCatsStr" />
is my hidden field that keeps the checked Sub Categories ids.

Search form, if no value go to site

I have a search form which searchers wikipedia.com. Nothing fancy, a form with an input.
If the input is empty, currently the user is redirected here: http://en.wikipedia.org/w/index.php?title=Special%3ASearch&redirs=1&search=&fulltext=Search&ns0=1 .
Id like to redirect the users here: www.wikipedia.com instead
How can I do this?
This is my search form:
<form method="get" action="http://en.wikipedia.org/w/index.php">
<input type="hidden" value="Special:Search" name="title"/>
<input type="hidden" value="1" name="redirs"/>
<input type="text" name="search">
<input type="hidden" value="Search" name="fulltext"/>
<input type="hidden" value="1" name="ns0"/>
</form>
It's not possible, I don't think, without using JavaScript; if, as you've indicated, you're willing to use jQuery:
$('form').submit(
function(){
if ($(this).find('input:text').val() == ''){
$(this).attr('action','http://www.wikipedia.com/');
}
else {
$(this).submit();
}
});
JS Fiddle demo.
In plain JavaScript, the following seems to work (tested in Chromium 12 and Firefox 7 on Ubuntu 11.04):
var formEl = document.getElementsByTagName('form')[0];
var inputs = formEl.getElementsByTagName('input');
var textInputEl = [];
for(i in inputs){
if (inputs[i].type == 'text'){
textInputEl.push(inputs[i]);
}
}
formEl.onsubmit = function(){
if (textInputEl.value === '' || textInputEl.value === null){
this.action = 'http://www.wikipedia.com/';
}
else {
formEl.submit;
}
};
JS Fiddle demo.
I'm trying to set this up so that, with an empty text-input, the form will remove any hidden elements and then set the action, or the document.location to be http://en.wikipedia.org/wiki/Special:Random. This does not, for some reason, seem to work. Almost as if Wikipedia's finding something wrong and then redirecting to a different page. Ungh. Anyways, this is what I tried:
$('form').submit(
function(){
if ($(this).find('input:text').val() == ''){
$(this).find('input:hidden').remove();
$(this).attr('action','http://en.wikipedia.org/wiki/Special:Random');
}
else {
$(this).submit();
}
});
JS Fiddle demo;
$('form').submit(
function(){
if ($(this).find('input:text').val() == ''){
$(this).find('input:hidden').remove();
document.location.href = 'http://en.wikipedia.org/wiki/Special:Random';
/*
I also tried 'document.location','window.location'
and 'window.location.href' all of which, predictably,
failed in exactly the same way.
*/
}
else {
$(this).submit();
}
});
JS Fiddle demo;