jQuery detecting changes on two elements using keyup() - javascript

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

Related

if statement echo out different links for different codes

I am using this code
HTML:
<div id="message">some message</div>
<input type="text" id="myInput" />​
jQuery:
$(function() {
$("#message").hide();
$("#fail").hide();
var prefix = ['HX', 'HD', 'BD', 'LS']
$('#myInput').keyup(function(e) {
var value = $(this).val();
var firstTwo = value.substr(0,2);
var firstTwoUpper = firstTwo.toUpperCase();
if(firstTwo != firstTwoUpper) {
$(this).val( value.replace(/^\w\w/, firstTwoUpper) );
}
if(value.length > 1) {
if($.inArray(firstTwoUpper, prefix) >= 0) {
$("#fail").hide();
$("#message:hidden").fadeIn();
} else {
$("#message").hide();
$("#fail:hidden").fadeIn();
}
} else {
$("#message").hide();
$("#fail").hide();
}
});
});
​
To be a post code check. I got the above code from here: Jquery check array perform function and it works just fine but I want to display a message containing a link which all differ from one another. For example I want code 'HX' to link to facebook and I want 'BD' to link to the BBC. How would I write the if statement correctly? I have tried various ways but I am not achieving what I need.
Could someone give me a little guideance please?
Thanks,
Ben.
This fiddle does what you might be looking for
<div id="message">Some link</div>
<div id="fail">Invalid postcode</div>
<input type="text" id="myInput" />
$(function () {
$("#message").hide();
$("#fail").hide();
var prefix = ['HX', 'HD', 'BD', 'LS'];
var links = ['http://www.facebook.com','http://www.example.com','http://www.bbc.com','#'];
$('#myInput').keyup(function (e) {
var value = $(this).val();
var firstTwo = value.substr(0, 2);
var firstTwoUpper = firstTwo.toUpperCase();
if (firstTwo != firstTwoUpper) {
$(this).val(value.replace(/^\w\w/, firstTwoUpper));
}
if (value.length > 1) {
var index = $.inArray(firstTwoUpper, prefix);
if (index >= 0) {
$("#fail").hide();
$("#message").fadeIn();
$("#message a").attr("href",links[index]).html(links[index])
} else {
$("#message").hide();
$("#fail:hidden").fadeIn();
}
} else {
$("#message").hide();
$("#fail").hide();
}
});
});
this fiddle: http://jsfiddle.net/um67M/2/
I changed prefix from an array of strings to an array of objects.
You're going to see an issue if users type really fast because of the speed of fadeIn().
$(function() {
$("#message").hide();
$("#fail").hide();
var prefix = [{code:'HX',link:'www.facebook.com'}, {code:'BD',link:'www.bbc.com'}];
$('#myInput').keyup(function(e) {
var value = $(this).val();
var firstTwo = value.substr(0,2);
var firstTwoUpper = firstTwo.toUpperCase();
if(firstTwo != firstTwoUpper) {
$(this).val( value.replace(/^\w\w/, firstTwoUpper) );
}
if(value.length > 1) {
for(var obj in prefix){
console.log(firstTwoUpper, prefix[obj].code, firstTwoUpper == prefix[obj].code);
if(firstTwoUpper === prefix[obj].code){
$("#fail").hide();
var link = ''+prefix[obj].link+'';
$("#message").append(link);
$("#message:hidden").fadeIn();
break;
}else {
$("#message").hide();
$("#fail:hidden").fadeIn();
}
};
} else {
$("#message").empty();
$("#message").hide();
$("#fail").hide();
}
});
});
$('#myInput').keyup(function (e) {
var value = $(this).val();
var firstTwo = value.substr(0, 2);
var firstTwoUpper = firstTwo.toUpperCase();
if (firstTwo != firstTwoUpper) {
$(this).val(value.replace(/^\w\w/, firstTwoUpper));
}
if (value.length > 1) {
if ($.inArray(firstTwoUpper, prefix) >= 0) {
if (firstTwoUpper == "HX") {
$("#message").empty();
$("#message").html('<p>some message</p>Google');
} else if (firstTwoUpper == "HD") {
$("#message").empty();
$("#message").html('<p>other message</p><a `enter code here`href="http://www.stackoverflow.com">Stack OverFlow</a>');
}
$("#fail").hide();
$("#message:hidden").fadeIn();
} else {
$("#message").hide();
$("#fail:hidden").fadeIn();
}
} else {
$("#message").hide();
$("#fail").hide();
}
});
the fiddle is here
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')); }

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

.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