Select text contents of multiple elements by class - javascript

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
});
}
}

Related

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

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);

jQuery detecting changes on two elements using keyup()

HTML:
<form>
<input type="text" id="target" placeholder="example.com">
<input type="checkbox" name="http" id="http" value="http"> http://
</form>
<div id="possible-targets">
<h4>Possible matches: </h4>
</div>
JS:
var target_value;
$(window).load(function () {
$('#target').keyup(function () {
target_value = $('#target').val();
if (target_value == '') {
$('#target-match').remove();
} else if ($('#target-match').length == 0) {
$('#possible-targets').append('<h4><span id="target-match">' + target_value + '</span></h4>');
} else if ($('#target-match').length != 0) {
$('#target-match').html(target_value);
}
if ($('#http').prop('checked')) {
if ($('#target-match-h').length == 0) {
$('#possible-targets').append('<h4><span id="target-match-h">http://' + target_value + '</span></h4>');
} else {
$('#target-match-h').html('http://' + target_value);
}
} else {
$('#target-match-h').remove();
}
});
});
Here is a JSFiddle: http://jsfiddle.net/h2Uw4/
Now when I start typing in the text input field I can see a live change in the possible-targets div, but when I click on the http:// checkbox it still needs to type at least one more character in the text input field to make a live change and add another possible target.
I tried to use keyup() on both #target (the text input) and #http (the checkbox) but it didn't work:
$('#target, #http').keyup()
Create a function and pass it to event handlers.
Example Code
var yourFunc = function () {
//Your code
};
$('#target').keyup(yourFunc);
$('#http').change(yourFunc);
DEMO
As per #DavidThomas comments you can also use
$('#target, #http').on('change keyup', yourFunc)
DEMO 2
Try this
var target_value;
$(window).load( function() {
$('#target').keyup(function() {
target_value = $('#target').val();
if(target_value == '') {
$('#target-match').remove();
} else if($('#target-match').length == 0) {
$('#possible-targets').append('<h4><span id="target-match">' + target_value + '</span></h4>');
} else if($('#target-match').length != 0) {
$('#target-match').html(target_value);
}
if($('#http').prop('checked')) {
if($('#target-match-h').length == 0) {
$('#possible-targets').append('<h4><span id="target-match-h">http://' + target_value + '</span></h4>');
} else {
$('#target-match-h').html('http://' + target_value);
}
} else {
$('#target-match-h').remove();
}
});
$('#http').click(function(){
if ($('#target').val() !== "")
if (this.checked === true) {
$('#possible-targets').html('<h4>Possible matches: </h4><h4><span id="target-match-h">http://' + target_value + '</span></h4>');
} else {
$('#possible-targets').html('<h4>Possible matches: </h4><h4><span id="target-match-h">' + target_value + '</span></h4>');
}
});
});
You will have to execute the callback functionality when the checkbox's value is changed.
please update the js as :
var target_value;
$(window).load( function() {
$('#target').keyup(displayMatches);
$('#http').change(displayMatches);
});
function displayMatches() {
target_value = $('#target').val();
if(target_value == '') {
$('#target-match').remove();
} else if($('#target-match').length == 0) {
$('#possible-targets').append('<h4><span id="target-match">' + target_value + '</span></h4>');
} else if($('#target-match').length != 0) {
$('#target-match').html(target_value);
}
if($('#http').prop('checked')) {
if($('#target-match-h').length == 0) {
$('#possible-targets').append('<h4><span id="target-match-h">http://' + target_value + '</span></h4>');
} else {
$('#target-match-h').html('http://' + target_value);
}
} else {
$('#target-match-h').remove();
}
}
updated fiddle

custom JS file prevents jquery from running

I have been working to get the jQuery UI Tabs to work with a site I'm working on. I was able to get it to work after commenting out a custom made javascript file that stops jQuery from running. I need to use this file but I am not sure what is wrong with the code that would keep jQuery from running. I would be grateful for any help. Thanks.
$(document).ready(function(){
initLimitedTextarea();
initPointsControls();
});
function initForms( id ){
$(id).bind('submit', function() {
if(id.toString().toLowerCase() == '#fm-registration'){
$(this).ajaxSubmit({ success: FinishRegistration });
} else if(id.toString().toLowerCase() == '#fm-join') {
$(this).ajaxSubmit({ success: FinishJoin });
} else {
console.log('Initializing...');
$(this).ajaxSubmit({ success: showResponse });
}
return false;
});
}
function FinishRegistration(responseText, statusText){
if(responseText.search(/NewNotify/) != -1 ){
$('#fm-registration').hide('slow').EffectChain({onComplete:function(){
$('#fm-registration').html(responseText);
$('#fm-registration').show('slow');
}});
} else {
showResponse(responseText, statusText);
}
}
function showResponse(responseText, statusText) {
if(responseText != '') {
$('#error-msg').html(responseText);
} else {
tb_remove();
}
}
function FinishJoin(responseText, statusText) {
//console.log(responseText);
if(responseText != '' && responseText.toLowerCase().search('viewtribe.php') == -1) {
$('#error-msg').html(responseText);
} else {
tb_remove();
window.location.href = responseText;
}
}
function hidePopup(){
$('#fade-area').animate({opacity:0}, 'fast').hide();
$('#container').html(' ');
//$('#container').fadeOut();
}
var specialKeys = [8,46,37,39,38,40,27,9,16,17,18,20,144];
function isSpecialKey(code){
for(i = 0; i < specialKeys.length; i++){
if(code == specialKeys[i]){ return true; }
}
return false;
}
function initLimitedTextarea(){
$('textarea.limited-size, input.limited-size').each(function(){
if ($(this).hasClass('edit')){
$('#' + $(this).attr('id') + '-monitor').html($(this).attr('size'));
$(this).keypress(function(e){
if(((parseInt($(this).attr('size')) - ($(this).val()).length)) <= 0 && !(specialKey = isSpecialKey(e.keyCode))){
return false;
}
});
$(this).keyup(function(e){
$('#' + $(this).attr('id') + '-monitor').html((parseInt($(this).attr('size')) - ($(this).val()).length));
});
}else{
$('#' + $(this).attr('id') + '-monitor').html($(this).attr('cols'));
$(this).keypress(function(e){
if(((parseInt($(this).attr('cols')) - ($(this).val()).length)) <= 0 && !(specialKey = isSpecialKey(e.keyCode))){
return false;
}
});
$(this).keyup(function(e){
$('#' + $(this).attr('id') + '-monitor').html((parseInt($(this).attr('cols')) - ($(this).val()).length));
});
}
});
}
function initPointsControls(){
$("input[name=completed[]], input[name=targeted[]]").each(function (i, el) {
$(el).bind('click', function(){
name = ($(this).attr('name').toLowerCase() == 'completed[]') ? 'targeted[]' : 'completed[]' ;
if($(this).attr('checked') == true && $("input[name=" + name + "][value=" + $(this).attr('value') + "]").attr('checked') == true){
$("input[name=" + name + "][value=" + $(this).attr('value') + "]").attr('checked', false);
}
});
});
}
function Activate( obj ){
$("#activation-done").load($(obj).attr('href'));
return false;
}
function delayer(){
window.location = 'GetRewards.php';
}
function confirmation() {
var answer = confirm('Are you sure you want to use reward points for this reward?');
if (answer){
setTimeout('delayer()', 1000);
return true;
}
else{
return false;
}
}
function SetData( value ){ $("input[name='profileimage']").val(value); }
function enableSubmit() { $('input[name="submitnew"]').attr('disabled', !$('#agree').attr('checked')); }

.selectable() multi-select from different criteria groups

I am trying to figure out how to best allow multi-selection between two different criteria groups. Right now, selecting Yellow and Small in my example will return all Yellow and all Small elements. I am hoping to return the intersection of Yellow and Small.
http://jsfiddle.net/RKxj7/16/
.selectable({selected: function () {
$("#table-content tr").hide();
if ($("#Red").is(".ui-selected")) {
$(".color:contains('Red')").showParent();
}
...
if ($("#Small").is(".ui-selected")) {
$(".size:contains('Small')").showParent();
}
Try this out:- http://jsfiddle.net/adiioo7/RKxj7/19/
JS:-
function toggleSelected() {
$("#table-content tr").hide();
var colorSelected = $(".selector .ui-selected").length;
var sizeSelected = $(".selector2 .ui-selected").length;
if ((colorSelected > 0 && sizeSelected == 0) || (colorSelected == 0 && sizeSelected > 0)) {
$(".selector").find(".ui-selected").each(function () {
$(".color:contains(" + $(this).text() + ")").showParent();
});
$(".selector2").find(".ui-selected").each(function () {
$(".size:contains(" + $(this).text() + ")").showParent();
});
} else {
$(".selector").find(".ui-selected").each(function () {
var selectedColor = $(".color:contains(" + $(this).text() + ")");
$(".selector2").find(".ui-selected").each(function () {
selectedColor.parent().find(".size:contains(" + $(this).text() + ")").showParent();
});
});
}
if ($(".ui-selected").length == 0) $("#table-content").find("tr").show();
}
$(document).ready(function () {
$.fn.showParent = function () {
$(this).parent().show();
};
$(".selector, .selector2").bind("mousedown", function (e) {
e.metaKey = true;
}).selectable({
selected: toggleSelected,
unselected: toggleSelected
});
});
...maybe this one?
.selectable({ selected: function () {
$("#table-content tr").show();
if (!$("#Red").is(".ui-selected")) {
$(".color:contains('Red')").hideParent();
}
http://jsfiddle.net/RKxj7/37/
Adding .css makes it colorful and the size is as selected:
http://jsfiddle.net/kjelenak/RKxj7/55/
function toggleSelected() {
$("#table-content tr").hide();
var colorSelected = $(".selector .ui-selected").length;
var sizeSelected = $(".selector2 .ui-selected").length;
if ((colorSelected > 0 && sizeSelected == 0) || (colorSelected == 0 && sizeSelected > 0)) {
$(".selector").find(".ui-selected").each(function () {
var colour = $(this).text();
$(".color:contains(" + $(this).text() + ")").css("color", colour).showParent();
});
$(".selector2").find(".ui-selected").each(function () {
$(".size:contains(" + $(this).text() + ")").showParent();
});
} else {
$(".selector").find(".ui-selected").each(function () {
var selectedColor = $(".color:contains(" + $(this).text() + ")");
$(".selector2").find(".ui-selected").each(function () {
var size = $(this).text(); selectedColor.parent().find(".size:contains(" + $(this).text() + ")").css("font-size", size).showParent();
});
});
}
if ($(".ui-selected").length == 0) $("#table-content").find("tr").show();
}
$(document).ready(function () {
$.fn.showParent = function () {
$(this).parent().show();
};
$(".selector, .selector2").bind("mousedown", function (e) {
e.metaKey = true;
}).selectable({
selected: toggleSelected,
unselected: toggleSelected
});
});
based on https://stackoverflow.com/a/19558160/3476753 (wiz kid)

Do not allow special characters jQuery

Have some error in this, can you guys please tell me what i am doing wrong
function verifyGroup(groupVal, errorid) {
groupVal = $.trim(groupVal);
if (groupVal != '') {
var splChars = "*|,\":<>[]{}`\';()#&$#%!+-";
for (var i = 0; i < groupVal.length; i++) {
console.log(groupVal.charAt(i)+' == '+splChars.indexOf(groupVal.charAt(i)));
if (splChars.indexOf(groupVal.charAt(i)) != -1) {
$("#" + errorid).addClass("form-error").html("Illegal characters detected!");
return false;
} else {
$("#" + errorid).removeClass("form-error").html("");
return true;
}
}
} else {
$("#" + errorid).addClass("form-error").html("Group name should not be empty");
return false;
}
}
DEMO
Use a regex
function verifyGroup(groupVal, errorid) {
groupVal = $.trim(groupVal);
console.log(groupVal);
console.log(errorid);
if (groupVal != '') {
var regex = /[*|,\\":<>\[\]{}`';()#&$#%!+-]/;
if(regex.test(groupVal)){
$("#" + errorid).addClass("form-error").html("Illegal characters detected!");
return false;
} else {
$("#" + errorid).removeClass("form-error").html("valid");
return true;
}
} else {
$("#" + errorid).addClass("form-error").html("Group name should not be empty");
return false;
}
}
$(function() {
// Handler for .ready() called.
$('#submit').click(function(){
verifyGroup($('#ipId_create').val(), 'error_id');
});
});
Demo: Fiddle
The comparison to -1 should be == not !=.

Categories

Resources