Jquery autocomplete in jsp - javascript

I am new in jsp and so in javascript and i am trying to create an autocomplete form with two text fields. Also i want the second one to take some value automatic according to the value of the first one. Well, i did a little research and i found in another topic a code snippet. The think is that when i put it in a single jsp page in netbeans it doesn't works.I think something is missing. Can you please help with that. Thanks.
Here is my code:
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<body>
<input id='fruit' name='fruit' type='text'>
<input id='details' name='details' type='text'>
<script>
var x = [
{ label : 'apple', value : 'Delicious' },
{ label : 'kiwi', value : 'Yummy' },
{ label : 'kiwiooo', value : 'aaa' },
{ label : 'lemon', value : 'Sour' }
];
$( "#fruit" ).autocomplete({
source: x,
focus : function(){ return false; }
})
.on( 'autocompleteresponse autocompleteselect', function( e, ui ){
var t = $(this),
details = $('#details'),
label = ( e.type === 'autocompleteresponse' ? ui.content[0].label : ui.item.label ),
value = ( e.type === 'autocompleteresponse' ? ui.content[0].value : ui.item.value );
t.val( label );
details.val( value );
return false;
});
</script>
</body>
</html>
FIDDLE
UPDATED

Related

How to let this JavaScript/jQuery script use HTML?

I'm trying to make my small website multilingual, and after testing many options, this script seems to be the best:
( https://jsfiddle.net/imihandstand/fh1rcy97/1/ . Source: https://stackoverflow.com/a/47612798/4024828 )
<script>
var LanguageList = {
"EN" : "English",
"ES" : "EspaƱol"
};
//languages Objects
var WORDS_EN = {
"text1" : "text One",
"text2" : "<b>text Two</b>"
};
var WORDS_ES = {
"text1" : "texto Un",
"text2" : "<b>texto Dos</b>"
};
window.onload = initialize;
function initialize() {
var $dropdown = $("#country_select");
$.each(LanguageList, function(key, value) {
$dropdown.
append($("<option/>").
val(key).
text(value));
});
loadsLanguage("EN");
}
function loadsLanguage(lang){
/*fills all the span tags with class=lang pattern*/
$('span[class^="lang"]').each(function(){
var LangVar = (this.className).replace('lang-','');
var Text = window["WORDS_"+lang][LangVar];
$(this).text(Text);
});
}
</script>
<select id="country_select" onchange="loadsLanguage(this.value);">
</select>
<div>
<span class="lang-text1"></span>
</div>
<div>
<span class="lang-text2"></span>
</div>
<div>
<span class="lang-text2"></span>/<span class="lang-text2"></span>
</div>
But I have one huge issue with it: It does not care about HTML-tags I use in it - but I would need that. So text in <b> should be shown as bold, etc.
How could I change this script to make it use the HTML-tags? I tried for 2-3 hours and I'm unable to solve it...
Thank you very much!

Create a hidden field, add it to form elements being sent on form submit? [duplicate]

How do you create a hidden field in JavaScript into a particular form ?
<html>
<head>
<script type="text/javascript">
var a =10;
function test() {
if (a ==10) {
// ... Here i need to create some hidden field for form named = chells
}
}
</script>
</head>
<body >
<form id="chells" name="formsdsd">
<INPUT TYPE=BUTTON OnClick="test();">
</form>
</body>
</html>
var input = document.createElement("input");
input.setAttribute("type", "hidden");
input.setAttribute("name", "name_you_want");
input.setAttribute("value", "value_you_want");
//append to form element that you want .
document.getElementById("chells").appendChild(input);
You can use jquery for create element on the fly
$('#form').append('<input type="hidden" name="fieldname" value="fieldvalue" />');
or other way
$('<input>').attr({
type: 'hidden',
id: 'fieldId',
name: 'fieldname'
}).appendTo('form')
I've found this to work:
var element1 = document.createElement("input");
element1.type = "hidden";
element1.value = "10";
element1.name = "a";
document.getElementById("chells").appendChild(element1);
insertAdjacentHTML does the trick, and is probably the easiest way, query for the parent, and then just ask to insert before the end, or after the beginning as you see fit, i.e:
document.querySelector('#chells').insertAdjacentHTML('beforeend',
"<input type='hidden' name='status' value='true' />")
You can use this method to create hidden text field with/without form. If you need form just pass form with object status = true.
You can also add multiple hidden fields.
Use this way:
CustomizePPT.setHiddenFields(
{
"hidden" :
{
'fieldinFORM' : 'thisdata201' ,
'fieldinFORM2' : 'this3' //multiple hidden fields
.
.
.
.
.
'nNoOfFields' : 'nthData'
},
"form" :
{
"status" : "true",
"formID" : "form3"
}
} );
var CustomizePPT = new Object();
CustomizePPT.setHiddenFields = function(){
var request = [];
var container = '';
console.log(arguments);
request = arguments[0].hidden;
console.log(arguments[0].hasOwnProperty('form'));
if(arguments[0].hasOwnProperty('form') == true)
{
if(arguments[0].form.status == 'true'){
var parent = document.getElementById("container");
container = document.createElement('form');
parent.appendChild(container);
Object.assign(container, {'id':arguments[0].form.formID});
}
}
else{
container = document.getElementById("container");
}
//var container = document.getElementById("container");
Object.keys(request).forEach(function(elem)
{
if($('#'+elem).length <= 0){
console.log("Hidden Field created");
var input = document.createElement('input');
Object.assign(input, {"type" : "text", "id" : elem, "value" : request[elem]});
container.appendChild(input);
}else{
console.log("Hidden Field Exists and value is below" );
$('#'+elem).val(request[elem]);
}
});
};
CustomizePPT.setHiddenFields( { "hidden" : {'fieldinFORM' : 'thisdata201' , 'fieldinFORM2' : 'this3'}, "form" : {"status" : "true","formID" : "form3"} } );
CustomizePPT.setHiddenFields( { "hidden" : {'withoutFORM' : 'thisdata201','withoutFORM2' : 'this2'}});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id='container'>
</div>

Retrieve value of Jquery autocomplete into Ajax call

I have a jquery autocomplete field in index.php page :
$html .= '<div class="ui-widget">
<label for="tags">Tags:</label>
<input id="tags" />
<div id="tagsname"></div>
</div>';
$html .= "<script>
jQuery.noConflict();
jQuery(function () {
var availableTags = [
'ActionScript',
'AppleScript',
'Asp',
'BASIC',
'C'
];
jQuery('#tags').autocomplete({
source: availableTags
});
});
jQuery(document).ready(function () {
jQuery('#tags').on('change', function () {
jQuery('#tagsname').html('You selected: ' + this.value);
}).change();
jQuery('#tags').on('autocompleteselect', function (e, ui) {
jQuery('#tagsname').html('You selected: ' + ui.item.value);
});
});</script>";
And I want to retrieve the value into my ajax call in ajax.js file:
jQuery.ajax({
type: "GET",
url: "setvalues.php",
data: {"event": event}
The call is made with setvalues.php :
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
$_SESSION['event'] = $_GET['event'];
Note: the ajax function is called onclick with a button.
So that was the context.
What I am trying to do is get the value from my jQuery input in my Ajax function.
What I've tried to do :
I've put this line :
event = jQuery('#tagsname').html(ui.item.value);
Into my ajax.js file just before the call to get the value I need but it doesn't work.
I get this error :
Uncaught ReferenceError : ui is not defined
I suppose there is another way to get the value of my input but I can't find how.
Note2 : You may notice I've omitted some lines, in my ajax.js file for example. This is for clarity.
Just use jQuery's val() function on an input element. I created a simplified example where a value of your input is displayed in the alert message. You can do the same in your Ajax call.
jQuery.noConflict();
jQuery(function () {
var availableTags = [
'ActionScript',
'AppleScript',
'Asp',
'BASIC',
'C'
];
jQuery('#tags').autocomplete({
source: availableTags
});
});
jQuery(document).ready(function () {
jQuery('#tags').on('change', function () {
jQuery('#tagsname').html('You selected: ' + this.value);
}).change();
jQuery('#tags').on('autocompleteselect', function (e, ui) {
jQuery('#tagsname').html('You selected: ' + ui.item.value);
});
});
// Click event handler of "Get value" button
jQuery("#getValue").click(function() {
// Select input element and take it's value using jQuery's val() function
var selValue = jQuery("#tags").val();
alert("Selected value: " + selValue);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>
<link href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" rel="stylesheet"/>
<div class="ui-widget">
<label for="tags">Tags:</label>
<input id="tags" />
<div id="tagsname"></div>
</div>
<button type="button" id="getValue">Get value</button>
to get a div value/text, you should try
let event = $('#tagsname').text();
to set value
$('element').text('some _value');
Update:
if you want to get input elements value, use jquery val() method
$('input_element').val();
in your case use,
$("#tags").val();

JQuery Autocomplete - show full menu on focus (from within WP shortcode)

I have a working autocomplete form. I would love it to show all the labels in the dropdown on a single click without having to type.
Stack exchange is full of great answers to this question and I have tried them all without success. I suspect the problem is that the whole thing is being loaded from within a Wordpress Shortcode. Would like to keep it that way if possible. Any help?
I have two inputs that use Autocomplete.
//create autocomplete compare box shortcode
function autocomparebox( $atts, $content = null ) {
return '
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.3/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.3/jquery-ui.js"></script>
<script>
$(function() {
var blenders = [
{
value: "optimum-9400",
label: "Optimum 9400",
icon: "2015/02/optimum-9400-blender-60x60.jpg"
},
{
value: "optimum-9200",
label: "Optimum 9200",
icon: "2015/02/optimum-9200-60x60.jpg"
},
{
value: "optimum-8200",
label: "Optimum 8200",
icon: "2015/02/optimum-8200-60x60.jpg"
}
];
//autocomplete Input 1
$( "#blender" ).autocomplete({
minLength: 0,
source: blenders,
focus: function( event, ui ) {
$( "#blender" ).val( ui.item.label );
return false;
},
select: function( event, ui ) {
$( "#blender" ).val( ui.item.label );
$( "#blender-id" ).val( ui.item.value );
$( "#blender-icon" ).attr( "src", "http://bestblenderaustralia.com.au/wp-content/uploads/" + ui.item.icon );
return false;
}
})
//Autocomplete Input 2
$( "#blender2" ).autocomplete({
minLength: 0,
source: blenders,
focus: function( event, ui ) {
$( "#blender2" ).val( ui.item.label );
return false;
},
select: function( event, ui ) {
$( "#blender2" ).val( ui.item.label );
$( "#blender-id2" ).val( ui.item.value );
$( "#blender-icon2" ).attr( "src", "http://bestblenderaustralia.com.au/wp-content/uploads/" + ui.item.icon );
return false;
}
})
.autocomplete( "instance" )._renderItem = function( ul, item ) {
return $( "<li>" )
.append( "<a>" + item.label + "<br></a>" )
.appendTo( ul );
};
});
// Focus on Input 1 on page load, focus on Input 2 after Input 1 option is selected
$(document).ready(function(){
$("#blender").focus();
$("#blender-icon").click(function(){
$("#blender").focus();
});
$("#blender-icon2").click(function(){
$("#blender2").focus();
});
$("#ui-id-1 li, #ui-id-1").click(function(){
/* if ($("#blender2").val().length > 0) {
$( "#compareform" ).submit();
} else { */
$("#blender2").focus();
// }
});
$("#ui-id-2 li, #ui-id-2").click(function(){
$("#blender").focus();
});
});
//Values of selected items are passed to URL
function compareurl(){
var url="http://bestblenderaustralia.com.au/" + document.getElementById("blender-id").value + "-vs-" + document.getElementById("blender-id2").value;
location.href=url;
return false;
}
//Make sure both inputs are filled before submission
function validateForm() {
var errorWarning = document.querySelector("#error-warning");
var successLoading = document.querySelector("#success-loading");
var x = document.forms["compareform"]["blender"].value;
var y = document.forms["compareform"]["blender2"].value;
if (x == null || x == ""|| y == null || y == "" || x == y) {
errorWarning.style.display = "block";
return false;
} else {
errorWarning.style.display = "none";
successLoading.style.display = "block";
return compareurl();
}
}
</script>
<form id="compareform" onSubmit="return validateForm();">
<div class="blender-compare-wrapper">
<div id="blender-label"></div>
<img id="blender-icon" src="http://bestblenderaustralia.com.au/wp-content/themes/x-child-icon/img/blender-thumb-placeholder.png" class="ui-state-default" alt="">
<input name="blendera" id="blender" placeholder="Type a blender..." onfocus="this.placeholder = """>
<input type="hidden" id="blender-id">
<span class="versus"> VS. </span>
<img id="blender-icon2" src="http://bestblenderaustralia.com.au/wp-content/themes/x-child-icon/img/blender-thumb-placeholder.png" class="ui-state-default" alt="">
<input name="blenderb" id="blender2" placeholder="Type a blender..." onfocus="this.placeholder = """>
<input type="hidden" id="blender-id2">
<input type="submit" id="comparesubmit" value="Compare">
<p id="error-warning">Please choose two different blenders.</p>
<p id="success-loading">Loading results...</p>
</form>
</div>
';}
//Add the shortcode
add_shortcode('autocomparebox', 'autocomparebox');
Thats not possible , because jquery autocomplete triggers only if any value changes inside the textblock , but showing all the labels is possible
Take a look at this Stack, but workaround in source will give you desired results
Thanks for your help, I did find a workaround and it's as easy as binding a focus event to fire off an empty Autocomplete search. Just replace #yourid with the ID of your input and you're good to go.
$("#yourid").bind("focus", function(){
if($(this).val()==""){
$(this).autocomplete("search");
}
});
Use the option minLengthset to 0
minLength: 0
Hope that helps

Radiobuttons and Checkboxes "checked" issue in Javascript

I have Javascript code using JQuery to create quizzes containing free text, radio buttons (single choice) and check boxes (multiple choice) questions. The quizzes are made using a web interface, with Zurb - Foundation for the style, and are being serialized in JSON. While creating the radio buttons and the check boxes answers for an specific question, when an user checks either component (to mark it as the valid answer, for example), it's supposed to validate this, and come as "true" (represented by the number "1") in the JSON.
It's currently working for the text type question, as it is basically hard-coded. But it's not doing the trick for the other two.
Here's the main pieces of code (If more is needed I'll edit the question): Whole quiz
storeQuiz: function( event ) {
var self = event.data;
var store = [];
$(self.element).find( '.question-content' ).each( function(){
var question = $( this );
var entry = { options: [] };
if ( question.parent().attr( 'class' ).match( /template/ ) ) {
return true;
}
entry['content'] = question.find( '.input' ).val();
entry['type'] = question.parent().attr( 'class' ).match( /quiz-(\w+)/ )[1];
question.find( '.option' ).each( function() {
var option = $( this );
var data = {};
if ( entry.type === 'text' ) {
data['valid'] = true;
} else {
data['valid'] = !!option.find( '.option-validation input' ).attr( 'checked' );
}
data['content'] = option.find( '.option-content textarea' ).val();
entry.options.push( data );
})
store.push( entry );
});
self.storeUpdate( store );
},
Radios:
buildRadios: function( data ) {
var tmpl = this.radiosHandler( {data: this} );
var self = this;
tmpl.find( '.option' ).remove();
tmpl.find( '.input' ).val( data.content );
$.each( data.options, function() {
var plus = tmpl.find( '.add' );
var option = self.addAnswer.call( plus, {data: self} );
option.find( '.option-validation input' ).attr( 'checked', this.valid );
option.find( '.option-content textarea' ).val( this.content );
});
},
Check boxes:
buildCheckboxes: function( data ) {
var tmpl = this.checkboxesHandler( {data: this} );
var self = this;
tmpl.find( '.option' ).remove();
tmpl.find( '.input' ).val( data.content );
$.each( data.options, function() {
var plus = tmpl.find( '.add' );
var option = self.addAnswer.call( plus, {data: self} );
option.find( '.option-validation input' ).attr( 'checked', this.valid );
option.find( '.option-content textarea' ).val( this.content );
});
},
its smarter if you use
$('input[type="checkbox"]').is(':checked');
return value is boolean
Do not use attr() when looking for checked values because it is actually a property so .prop() should be used.
if($('input[type="checkbox"]').prop('checked') === true)
{
// checkbox is checked, uncheck it
$('input[type="checkbox"]').prop('checked', false);
}
else
{
// checkbox is unchecked, check it
$('input[type="checkbox"]').prop('checked', true);
}
If you want to get fancy:
$('input[type="checkbox"]').on('change', function(){
if($(this).prop('checked')){
alert('TRUE : checked');
}
else{
alert('FALSE : unchecked');
}
});
This is the reason that <input type="checkbox" checked> works without needing to do <input type="checkbox" checked="checked">
When you check a checkbox with your mouse then the DOM object's property is set to Boolean TRUE and unchecking switches it to Boolean FALSE
There is another easy way ..
if($('inputSelector')[0].checked == true) {
}
to set the checkbox use
$('inputSelector')[0].checked = true / false;
I solved my problem thanks to a friend with this fix:
data['valid'] = !!option.find( '.option-validation input' ).attr( 'checked' );
Changed to:
data['valid'] = option.find( '.option-validation input' ).is( ':checked' );

Categories

Resources