on.change() event doesn't run when manually setting value of <select> - javascript

As the title describes, I'm having a problem with a function running using the
$("element_name").on("change", some_function)
event on a select when manually setting the element's value like
$("element_name").val("")
I read something about a "chosen" and I don't understand what that has anything to do with the issue.
Anybody know why the on.change() handler isn't catching the manual value change?
EDIT: I am including additional information as the solutions suggested do not work.
trigger("change"), bind("change", and on("change") do not work.
This is the code for the recreated select that controls the value setting:
(function($) {
$.extend({
fancySelect: function(options) {
var defaults = {
autoClose: true
}
var options = $.extend(defaults, options);
$("select").hide();
$("select").each(function() {
var $select = $(this);
var $fancyselect = $('<div class="fancyselect"/>');
$select.after($fancyselect);
var $ul = $('<ul/>').appendTo($fancyselect);
$ul.hide();
var $options = $select.find("option");
var $span = $("<div/>").addClass("fancyselect-label").prependTo($fancyselect);
var $arrow = $("<div>▼</div>").addClass("fancyselect-arrow").appendTo($fancyselect);
var selected = $select.find("option[selected=selected]");
var toUse = 0;
if (selected.length == 0) {
toUse = $options.first();
} else {
toUse = selected.first();
}
$span.text(toUse.text());
$options.each(function() {
var $option = $(this);
var label = $option.text();
var value = $option.val();
if ($option.is(":selected")) {
$span.text(label);
}
var $li = $('<li value="' + value + '">' + label + '</li>').appendTo($ul).bind("click", function() {
$select.val(value);
if ($option.index() == $(this).index()) {
$options.removeAttr("selected");
$option.attr("selected", "selected");
}
$span.html(label);
if (options.autoClose) {
$ul.hide();
$fancyselect.removeClass("active");
}
$ul.find("li").removeAttr("class");
$(this).addClass("selected");
});
if ($option.is(":selected")) {
$li.addClass("selected");
}
});
if (!$select.attr("disabled")) {
var $j = 0;
$span.bind("click", function() {
if ($ul.is(":visible")) {
$ul.hide();
$fancyselect.removeClass("active");
$arrow.html("▼");
} else {
$(".fancyselect").each(function() {
$(this).find("ul").hide();
$(this).removeClass("active");
});
$ul.show();
$fancyselect.addClass("active");
$arrow.html("▼");
if ($j == 0) $ul.tinyScrollbar();
$j++;
}
});
} else {
$fancyselect.addClass("disabled");
}
});
$(document).bind("keyup keydown keypress", function(event) {
$(".fancyselect").each(function() {
var $ul = $(this).find("ul");
if ($ul.is(":visible")) {
var keycode = parseInt((event.keyCode ? event.keyCode : event.which));
if(keycode >= 48 && keycode <= 90){
$ul.find("li").each(function() {
if ($(this).text().substr(0, 1) == String.fromCharCode(event.keyCode)) {
$ul.find("li").removeAttr("class");
$(this).addClass("selected");
return;
}
});
} else if (keycode == 13) {
$ul.hide();
}
return;
}
});
});
}
});
})(jQuery);
$.fancySelect();
And this is the code for the binding:
$(".downloads-series-sort select").trigger("change", load_downloads);

Related

Job For Wordpress by blueglass plugin apply button validation API

i want to insert following Java Script into my Wordpress plugin
please help me
this what i written which validate from Sheetsu API
Details at - https://codepen.io/santosh-panda/pen/YOedWv?editors=1010
<input id="input-text_flacement-id">
<script src="https://script.sheetsu.com/"></script>
<script>
var input = document.getElementById('input-text_flacement-id');
var is_focused = false;
input.onfocus = function () {
is_focused = true;
}
input.onblur = function () {
if (is_focused) {
is_focused = false;
check_id(input.value);
}
}
function check_id(id) {
if (id.match(/\d{4}-\d{4}-\d{4}/)) {
document.body.append("\nchecking...");
function successFunc(data) {
var row = data.filter((row)=>row['adhar_no'] == id)
if(row.length){
document.body.append("\nid found");
}
else{
document.body.append('\nid not found');
}
}
// Get all rows where column 'adhar_no' is '3894-8873-7149'
var searchQuery = {
status: 'active',
};
Sheetsu.read("https://sheetsu.com/apis/v1.0dh/dd98887de543/", {
search: searchQuery
}, successFunc);
}
else {
document.body.append('\ninvalid id');
}
}
</script>
this code ^^ want to inster in Wordpress plugin JS
which excutive in http://www.flacement.com/jobssearch/iffco-tokio-job-in-jharsuguda/
i want it when some one apply [apply text field 1
in flacement ID it should validate from JS API if found then procedd or if not then invalide as first code. code is ready but i am confuse where to instert in follwing so it start working
Number.prototype.clamp = function(min, max) {
return Math.min(Math.max(this, min), max);
};
(function($){
$.fn.filterFind = function(selector) {
return this.find('*') // Take the current selection and find all descendants,
.addBack() // add the original selection back to the set
.filter(selector); // and filter by the selector.
};
$.fn.svgDraw = function(progress) {
this.filterFind('path').each(function() {
var pathLength = this.getTotalLength();
$(this).css('strokeDasharray', pathLength + ' ' + pathLength);
$(this).css('strokeDashoffset', pathLength * ((1 - progress)).clamp(0, 1));
});
return this;
};
$(document).ready(function(){
if( $('.jobs-modal').length ){
setTimeout(function(){
$('.jobs-modal').removeClass('hide');
}, 500);
$('.jp-apply-button').click(function(e){
e.preventDefault();
$('body').addClass('jobs-modal-open');
$('.jobs-modal').addClass('open');
});
$('.jobs-modal .modal-close').click(function(e){
e.preventDefault();
$(this).parents('.jobs-modal').removeClass('open');
$('body').removeClass('jobs-modal-open');
});
$('.jobs-modal-content').each(function(k){
$(this).find( '.inputfile' ).each(function(k){
var label = this.nextElementSibling;
var labelVal = label.innerHTML;
$(this).change(function(e){
var fileName = '';
if( this.files && this.files.length > 2 )
fileName = ( this.getAttribute( 'data-multiple-caption' ) || '' ).replace( '{count}', this.files.length );
else
fileName = e.target.value.split( '\\' ).pop();
if( fileName ){
label.querySelector( 'span' ).innerHTML = fileName;
var num = $(this).parents('.modal-input-fileinput').attr('data-files');
num = Number(num) + 1;
$(this).parents('.modal-input-fileinput').attr('data-files', num);
}else{
label.innerHTML = labelVal;
}
});
$(this).focus(function(){ $(this).addClass('has-focus') });
$(this).blur(function(){ $(this).removeClass('has-focus') });
});
});
if( $('.choose_file_multi_add').length ){
var i = 1;
$('.choose_file_multi_add').click(function(e){
e.preventDefault();
var key_id = $(this).data('key');
var parent = $(this).parents('.modal-input-fileinput');
var input = $('#file-input-tpl-'+key_id).html();
var label = $('#file-label-tpl-'+key_id).html();
var id = key_id + '-'+i;
var key = key_id + '-key-'+i;
input = input.replace( '{id}', id ).replace( '{id}', id ).replace( '{id}', id );
input = input.replace( '{nr}', i ).replace( '{nr}', i ).replace( '{nr}', i );
input = input.replace( '{key}', key ).replace( '{key}', key ).replace( '{key}', key );
label = label.replace( '{id}', id ).replace( '{id}', id ).replace( '{id}', id );
$(input).insertBefore( $('#'+key_id+' .choose_file_multi_add') );
$(label).insertBefore( $('#'+key_id+' .choose_file_multi_add') );
//parent.prepend( input );
//parent.prepend( label );
$('#'+id).change(function(e){
var fileName = '';
if( this.files && this.files.length > 1 )
fileName = ( this.getAttribute( 'data-multiple-caption' ) || '' ).replace( '{count}', this.files.length );
else
fileName = e.target.value.split( '\\' ).pop();
if( fileName ){
$('#label-'+id).find('span.name').text( fileName );
var num = $(this).parents('.modal-input-fileinput').attr('data-files');
num = Number(num) + 1;
$(this).parents('.modal-input-fileinput').attr('data-files', num);
}
});
$('.choose_file_multi .remove').click(function(e){
e.preventDefault();
var id = $(this).parents('.choose_file_multi').attr('id');
id = id.replace('label-', 'jobgroup-');
var num = $(this).parents('.modal-input-fileinput').attr('data-files');
num = Number(num) - 1;
$(this).parents('.modal-input-fileinput').attr('data-files', num);
$('.'+id).remove();
recalculateInputs();
return false;
});
$('#'+id).click();
recalculateInputs();
i++;
});
}
function recalculateInputs(){
if( $('.modal-input-fileinput.multiple .modal-input-multifile').length == 0 ){
$('.disabled-file-placeholder').addClass('input-reqired');
}else{
$('.disabled-file-placeholder').removeClass('input-reqired');
}
}
function validateEmail(email) {
var re = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
}
var sending_form = false;
$('.progress-button .progress-circle').svgDraw(0);
$("form#jobs-modal-form").submit(function(e){
e.preventDefault();
var self = this;
var toreturn = true;
$('#jobs-modal-form .input-reqired').each(function(){
var value = $(this).val();
var is_checked = false;
if( $(this).hasClass('input-job_email') ){
if( value == '' || !validateEmail(value) ){
$(this).addClass('alert').parents('.jobs-modal-input').addClass('alert');
toreturn = false;
}else{
$(this).removeClass('alert').parents('.jobs-modal-input').removeClass('alert');
}
}else if( $(this).hasClass('modal-input-checkbox') ){
var checkboxes_checked = 0;
$(this).parents('.checkbox_field').find('input[type="checkbox"]').each(function(){
var checked = $(this).prop('checked');
if( checked == true ){
checkboxes_checked++;
}
});
if( checkboxes_checked == 0 ){
$(this).addClass('alert').parents('.jobs-modal-input').addClass('alert');
toreturn = false;
}else{
$(this).removeClass('alert').parents('.jobs-modal-input').removeClass('alert');
}
}else if( $(this).hasClass('modal-input-radio') ){
var checkboxes_checked = 0;
$(this).parents('.radio_field').find('input[type="radio"]').each(function(){
var checked = $(this).prop('checked');
if( checked == true ){
checkboxes_checked++;
}
});
if( checkboxes_checked == 0 ){
$(this).addClass('alert').parents('.jobs-modal-input').addClass('alert');
toreturn = false;
}else{
$(this).removeClass('alert').parents('.jobs-modal-input').removeClass('alert');
}
}else{
if( value == '' ){
$(this).addClass('alert').parents('.jobs-modal-input').addClass('alert');
toreturn = false;
}else{
$(this).removeClass('alert').parents('.jobs-modal-input').removeClass('alert');
}
}
});
var input = document.getElementById('input-text_flacement-id');
var is_focused = false;
input.onfocus = function () {
is_focused = true;
}
input.onblur = function () {
if (is_focused) {
is_focused = false;
check_id(input.value);
}
}
function check_id(id) {
if (id.match(/\d{4}-\d{4}-\d{4}/)) {
document.body.append("\n checking...");
function successFunc(data) {
var row = data.filter((row)=>row['adhar_no'] == id)
if(row.length){
document.body.append("\n id found");
}
else{
document.body.append('\n id not found');
}
}
// Get all rows where column 'adhar_no' is '3894-8873-7149'
var searchQuery = {
status: 'active',
};
Sheetsu.read("https://sheetsu.com/apis/v1.0dh/dd98887de543/", {
search: searchQuery
}, successFunc);
} else {
document.body.append('\n invalid id');
}
}
if( toreturn && sending_form == false ){
/*
var progressBTN = $(self).find('.progress-button');
progressBTN.addClass('loading');
var progressCRCL = $(self).find('.progress-circle');
var progress = 0;
var intervalId = setInterval(function() {
progress += Math.random() * 0.5;
progressCRCL.svgDraw(progress);
if(progress >= 1) {
clearInterval(intervalId);
}
}, 200);
*/
sending_form = true;
$('.job-submit').hide();
$('.jobs-sending').show();
var formData = new FormData($("form#jobs-modal-form")[0]);
$.ajax({
type: 'POST',
url: jpsd.ajaxurl,
data: formData,
processData: false,
contentType: false,
success: function (data) {
//clearInterval(intervalId);
//progressCRCL.svgDraw(1);
// Clear all smaces and newlines that can happen on response on some servers
data = data.replace(/\s/g, "");
if( data == 'ok' ){
//setTimeout(function(){
// $(self).find('.progress-button').addClass('success');
//}, 500);
//setTimeout(function(){
$(self).slideUp();
$('#job-apply-confirmation').slideDown();
//}, 1000);
}else{
//setTimeout(function(){
// $(self).find('.progress-button').addClass('error');
//}, 500);
//setTimeout(function(){
$('.jobs-sending').hide();
//}, 1000);
}
return false;
},
});
return false;
}
return false;
});
/*
$('.progress-button').on('click', function() {
var $button = $(this);
$(this).addClass('loading');
var $progress = $(this).find('.progress-circle');
var progress = 0;
var intervalId = setInterval(function() {
progress += Math.random() * 0.5;
$progress.svgDraw(progress);
if(progress >= 1) {
clearInterval(intervalId);
//console.log("cleared interval");
$button.removeClass('loading');
if($button.attr('data-result') == "true") {
$button.addClass('success');
}
else {
$button.addClass('error');
}
}
}, 300);
// Now that we finished, unbind
$(this).off('click');
});
*/
} // end .jobs-modal length
});
})(jQuery);

Jquery selectbox strong tag help required

I am using Jquery NiceSelect Plugin for my select boxes but I want a little change in it i.e.
I want to use the strong or b tag in options but this plugin automatically converts html into
<label class="nice_label">Some Text Etc</label>
and into this
<p class="top">Some Text Etc</p>
but I want to exclude the conversion of strong tag or bold tag so that it would work like this
<label class="nice_label">Some Text <strong>Etc</strong></label>
Here is my JS
(function ( $ ) {
$.fn.niceselect = function()
{
return this.each(function(index,value)
{
/*SET VARIABLES
============================*/
var name = $(this).attr('name')
var select = $(this);
var num = index;
var multi = false;
var multix = '';
var type= 'radio';
var required = '';
var classes = '';
var selected = '';
var placeholder = 'Select';
if(select.attr('multiple') !== undefined)
{
multi = true;
multix = '[]';
type= 'checkbox';
}
if($(this).attr('class') !== undefined)
{
var classes = $(this).attr('class');
}
if(select.find('[value="placeholder"]').length > 0)
{
placeholder = select.find('[value="placeholder"]').html();
}
if(typeof( select.attr('required') ) != 'undefined')
{
required = 'required';
}
/*WRAP SELECT IN DIV
-------------------------*/
select.wrap('<div class="select_style '+classes+'"/>');
$('<span class="selectcon"> </span>').insertBefore(select);
/*CREATE PLACEHOLDER + OPTION BOX
--------------------------------------------*/
$('<div class="niceselect '+name+'" data-multi="'+multi+'"><p class="top">'+placeholder+'</p><div class="value_wrapper"></div></div>').insertBefore(this)
/*CREATE OPTGROUP BOXES
--------------------------------------------*/
if(select.find('optgroup').length > 0)
{
select.find('optgroup').each(function(key, opt){
select.siblings('.niceselect').children('.value_wrapper').append('<div class="opt opt'+key+'"><span class="optTitle">'+$(opt).attr('label')+'</span></div>')
$(opt).find('option').each(function(index,value){
var val;
if($(this).val() == '')
{
val = $(this).html();
}
else
{
val = $(this).val();
}
var txt = $(this).html();
selected = '';
if(typeof( $(this).attr('selected') ) != 'undefined')
{
selected = 'checked';
select.siblings('.niceselect').find('p.top').html(txt)
}
select.siblings('.niceselect').find('.opt'+key).append('<div class="values"><input type="'+type+'" '+required+' '+selected+' style=" pointer-events: none;" name="'+name+multix+'" value="'+val+'" data-text="'+txt+'" id="'+index+name+index+'" /> <label class="nice_label" >'+txt+'</label></div>')
})
})
}
/*CREATE GENERAL OPTION FIELDS*/
else
{
select.find('option').each(function(index,value){
var $this = $(this);
var val;
if($(this).val() == '')
{
val = $(this).html();
}
else
{
val = $(this).val();
}
var txt = $(this).html();
selected = '';
if(typeof( $(this).attr('selected') ) != 'undefined')
{
selected = 'checked';
select.siblings('.niceselect').find('p.top').html(txt)
}
select.siblings('.niceselect').children('.value_wrapper').append('<div class="values"><input type="'+type+'" '+required+' '+selected+' style=" pointer-events: none;" name="'+name+multix+'" value="'+val+'" data-text="'+txt+'" id="'+index+name+index+'" /> <label class="nice_label" >'+txt+'</label></div>')
})
}
select.remove()
select.attr('name','blobla')
/*BIND CLICK FUNCTIONS (hide / show menu)
===========================================*/
$('body').on('click',function()
{
$('.niceselect .value_wrapper').hide();
$('.select_style').removeClass('active')
})
$('body').on('click','.niceselect',function(e)
{
e.stopImmediatePropagation();
if($(this).parent().hasClass('active'))
{
$(this).find('.value_wrapper').hide();
$(this).parent().removeClass('active');
console.log('here')
}
else
{
//$('.niceselect .value_wrapper').hide();
$(this).children('.value_wrapper').show()
$(this).parent().addClass('active')
}
})
/*BIND CLICK FUNCTIONS (check values / update visual)
=====================================================*/
$('body').on('click','.niceselect .value_wrapper .values',function(e){
e.stopImmediatePropagation();
var checkBoxes = $(this).find('input');
var par = $(this).parent().parent();
if(par.attr('data-multi') == 'true')
{
if($(this).hasClass('active'))
{
$(this).removeClass('active');
}
else
{
$(this).addClass('active');
}
}
else
{
$(this).parent().parent().find('input[checked]').removeAttr('checked')
$(this).parent().parent().find('.active').removeClass('active');
if($(this).hasClass('active'))
{
$(this).removeClass('active');
}
else
{
$(this).addClass('active');
}
$('.niceselect .value_wrapper').hide();
$('.select_style').removeClass('active')
}
checkBoxes.prop("checked", !checkBoxes.prop("checked"));
checkBoxes.trigger('change')
})
$('body').on('click','.niceselect .value_wrapper .values label',function(e){e.preventDefault()})
$('body').on('change','.niceselect .values input',function(e){
var par = $(this).closest('.niceselect')
if(par.attr('data-multi') == 'true')
{
var number = par.find('input:checked').length;
par.find('p.top').html(number + ' Selected')
}
else
{
par.find('p.top').html($(this).attr('data-text'))
}
})
/*SEARCH OPTIONS IN SELECT BOX
----------------------------------------*/
var string = '';
$('body').on('keypress',function(e){
if($('.value_wrapper').is(':visible'))
{
var clearString;
$('.value_wrapper .highlight').removeClass('highlight')
clearInterval(clearString)
string = string+String.fromCharCode(e.which);
if(string.length == 1)
{
string = string.toUpperCase();
}
var thing = $('.value_wrapper:visible').find('label:contains('+string+')').first();
$(thing).parent().addClass('highlight')
if($('.value_wrapper:visible').find('.highlight').length > 0)
{
$('.value_wrapper:visible').stop().scrollTop($('.value_wrapper:visible').scrollTop() + $('.highlight').position().top)
}
clearString = setTimeout(function(){string = ''},500);
}
})
})
}
}( jQuery ));
I think that you want to do this:
/*CREATE GENERAL OPTION FIELDS*/
else
{
select.find('option').each(function(index,value){
var $this = $(this);
var val;
if($(this).val() == '')
{
val = $(this).html();
}
else
{
val = $(this).val();
}
var txt = $(this).html();
selected = '';
if(typeof( $(this).attr('selected') ) != 'undefined')
{
selected = 'checked';
select.siblings('.niceselect').find('p.top').html(txt)
}
select.siblings('.niceselect').children('.value_wrapper').append('<div class="values"><input type="'+type+'" '+required+' '+selected+' style=" pointer-events: none;" name="'+name+multix+'" value="'+val+'" data-text="'+txt+'" id="'+index+name+index+'" /> <label class="nice_label" ><b>'+txt+'</b></label></div>')
})
}
select.remove()
select.attr('name','blobla')
Notice that I only have changed this line:
select.siblings('.niceselect').children('.value_wrapper').append('<div class="values"><input type="'+type+'" '+required+' '+selected+' style=" pointer-events: none;" name="'+name+multix+'" value="'+val+'" data-text="'+txt+'" id="'+index+name+index+'" /> <label class="nice_label" ><b>'+txt+'</b></label></div>')
Copy & paste this part of the code and test it.

selections validation by value with jquery

I have 5 select fields with id's id1, id2,.. id5
and i need check if values (selected) not equal then highlight green and if equal then highlight red
but is look crazy validate each field 5 times? is posible use special functions ir validate easy than with:
if
if
if
if
I dont need a code just idea.
You can loop through each select to compare the values
$("select").change(function () {
flag = false;
var value = $(this).val();
$("select").each(function () {
if ($(this).val() != value)
flag = true;
});
if (flag)
$("select").css("color", "red");
else
$("select").css("color", "green");
});
Demo
Edit
$("select").change(function () {
var flag = true;
$("select").each(function () {
var outer = this;
$("select").not(outer).each(function () {
if ($(outer).val() == $(this).val()) {
flag = false;
return false;
}
});
});
if (flag)
$("select").css("color", "green");
else
$("select").css("color", "red");
});
Updated Fiddle
New update
I've simplified the code like this. YOu dont have to use nested loop if you do like this
$("select").change(function () {
var flag = true;
$("select").each(function () {
if ($("select").find("option:selected[value=" + this.value + "]").length > 1) {
flag = false;
return false;
}
});
if (flag)
$("select").css("color", "green");
else
$("select").css("color", "red");
});
Updated Fiddle
Try this one..
$("select").change(function(){
var selected = [];
var valiSel = [];
$('select > option:selected').each(function() {
if($(this).val() != 0){
selected.push( $(this).val() );
}
valiSel.push( $(this).val() );
});
var unique = unique12(selected);
var uniqueLength = unique.length;
var valiSelUnique = unique12(valiSel);
var selectedLength = selected.length;
if( unique.length != selected.length ){
alert( 'Two Selected value cannot be same' );
return false;
}
//return true;
});
function unique12(sel) {
var r = new Array();
o:for(var i = 0, n = sel.length; i < n; i++)
{
for(var x = 0, y = r.length; x < y; x++)
{
if(r[x]==sel[i])
{
//alert('this is a DUPE!');
continue o;
}
}
r[r.length] = sel[i];
}
return r;
}
DEMO

Select text contents of multiple elements by class

I want to make a search demo. My problem is that I have one parent div in which I have two child divs. Both child divs have same class (RLTRightDiv). I want to search on all content. Can you please tell me how I can achieve that. It is currently only searching the first child of the parent div.
example "leave" is present in both div.
http://jsfiddle.net/3MVNj/5/
var searchIndex = -1;
var searchTermOld = '';
$(document).ready(function () {
/*
Search Functionality method.
*/
$('.searchbox').on('change', function () {
if ($(this).val() === '') {
var selector = "#fullContainer .RLTRightDiv";
$(selector + ' span.match').each(function () {
$(this).replaceWith($(this).html());
});
}
searchIndex = -1;
$('.searchNext').attr("disabled", "disabled");
$('.searchPrev').attr("disabled", "disabled");
searchTermOld = $(this).val();
});
$('.searchbox').on('keyup', function () {
var selector = "#fullContainer .RLTRightDiv";
if ($(this).val() === '') {
$(selector + ' span.match').each(function () {
$(this).replaceWith($(this).html());
});
}
if ($(this).val() !== searchTermOld) {
$(selector + ' span.match').each(function () {
$(this).replaceWith($(this).html());
});
searchIndex = -1;
$('.searchNext').attr("disabled", "disabled");
$('.searchPrev').attr("disabled", "disabled");
}
});
//Search Click method
$('.search').on('click', function () {
if (searchIndex == -1) {
var searchTerm = $('.searchbox').val();
if (searchTerm == '') {
PG_alert("Please Insert Text.")
return;
}
if (searchTerm == 'b'||searchTerm == 'br'||searchTerm == 'r') {
return;
}
setTimeout(function(){
searchAndHighlight(searchTerm);
},300);
} else
{
//naveen
setTimeout(function(){
searchNext();
},300);
}
if ($('.match').length > 1) {
$('.searchNext').removeAttr("disabled");
$('.searchPrev').removeAttr("disabled");
}
});
$('.searchNext').on('click', searchNext);
});
/*
Seacrh and highlight text method.
*/
function searchAndHighlight(searchTerm) {
if (searchTerm) {
var searchTermRegEx, matches;
var selector = "#fullContainer .RLTRightDiv";
$(selector + ' span.match').each(function () {
$(this).replaceWith($(this).html());
});
try {
searchTermRegEx = new RegExp('(' + searchTerm + ')', "ig");
} catch (e) {
return false;
}
$('.highlighted').removeClass('highlighted');
matches = $(selector).text().match(searchTermRegEx);
if (matches !== null && matches.length > 0) {
var txt = $(selector).html().replace(searchTermRegEx, '<span class="match">$1</span>');
$(selector).html(txt);
searchIndex++;
$('.match:first').addClass('highlighted');
$('#realTimeContents').animate({
scrollTop: $('.match').eq(searchIndex).get(0).offsetTop
});
return true;
} else {
console.log("yes===========")
searchIndex = -1;
}
return false;
}
return false;
}
function searchNext() {
var searchTerm = $('.searchbox').val();
if (searchTerm == '') {
PG_alert("Please Insert Text.")
return;
}
if (searchTerm == 'b'||searchTerm == 'r'||searchTerm == 'br') {
// PG_alert("Please .")
return;
}
if(searchIndex!=-1){
searchIndex++;
if (searchIndex >= $('.match').length) {
//naveen end
searchIndex = -1;
}
$('.highlighted').removeClass('highlighted');
$('.match').eq(searchIndex).addClass('highlighted');
$('#realTimeContents').animate({
scrollTop: $('.match').eq(searchIndex).get(0).offsetTop
});
}
}

AutoComplete (AutoFilter?), using jQuery delegate

$('#container form').delegate('#addSearch', 'keyup', function(e) {
var tmpVAL = $('#addSearch').val();
$('.w').each(function() {
var tmpHTML = $(this).html();
if (tmpHTML == tmpVAL) {
$(this).fadeIn(250);
} else if (tmpVAL.length < 1) {
$(this).fadeIn(250);
} else {
$(this).fadeOut(250);
}
});
});
and #addSearch is an <input type="text">.
So, my problem is that; this obviously will only return the results that are an exact match to the tmpVAL - How would I allow it so every letter will change the search result.
e.g.
I type N
it comes up with No, Not, Nothing, Nothingness
I type NOT
it comes up with Not, Nothing, Nothingness
Any help would be appreciated, I would imagine that it would be RegEx?
DEMO https://so.lucafilosofi.com/autocomplete-autofilter-using-jquery-delegate
$(function() {
$('#container form').delegate('#addSearch', 'keyup', function(e) {
var tmpVAL = $('#addSearch').val();
$('.w').each(function() {
var tmpHTML = $(this).text();
var subSection = tmpHTML.substring(tmpVAL.length, 0);
if (subSection == tmpVAL && tmpVAL != '' ) {
$(this).show();
} else {
$(this).hide();
}
});
});
});
You could use a regular expression, but I think that might be overkill. You could just use indexOf:
$('#container form').delegate('#addSearch', 'keyup', function(e) {
var tmpVAL = $('#addSearch').val().toLowerCase();
$('.w').each(function() {
var tmpHTML = $(this).html().toLowerCase();
if (tmpHTML.indexOf(tmpVAL) >= 0) {
$(this).fadeIn(250);
} else if (tmpVAL.length < 1) {
$(this).fadeIn(250);
} else {
$(this).fadeOut(250);
}
});
});
Working example: http://jsfiddle.net/andrewwhitaker/PRyvU/
Here's an alternative solution that doesn't use an .each():
$('#container form').delegate('#addSearch', 'keyup', function(e) {
var tmpVAL = $('#addSearch').val().toLowerCase();
var $words = $(".w");
var contains = function(haystack, needle) {
return haystack.indexOf(needle) >= 0;
};
if (tmpVAL.length < 1) {
$words.fadeIn(250);
}
else {
$words.filter(function() {
return !contains($(this).html().toLowerCase(), tmpVAL);
}).fadeOut(250);
$words.filter(function() {
return contains($(this).html().toLowerCase(), tmpVAL);
}).fadeIn(250);
}
});
http://jsfiddle.net/andrewwhitaker/EyJ6b/

Categories

Resources