javascript: Split an HREF string using a hash character - javascript

I have the following code that returns the url of each of the links in the function:
var nav_link;
$('#nav_what-we-do').find('.top-dropdown').find('a').each(function(index, elem) {
console.log("Descendant: " + elem.tagName + " " + elem.href);
the_link = $(this);
nav_link = elem.href.split('#');
if (nav_link[0] === '/what-we-do/') {
the_link.attr('href','#'+nav_link[1]);
the_link.click(function() {
var tab_id = $(this).attr('href');
selectTab(tab_id);
return false;
});
}
});
The console prints links like:
Descendant: A http://localhost/testsite/what-we-do/#solutions
Descendant: A http://localhost/testsite/what-we-do/#features
Descendant: A http://localhost/testsite/what-we-do/features/test
Descendant: A http://localhost/testsite/what-we-do/solutions/test2
Now I want only those links that contain the hash(#) and split them using this hash.
Then I want to check if array(0) contains the characters "/what-we-do/".
I have tried to split the links like this:
nav_link = elem.href.split('#');
but the IF part is not working.
Can someone tell me what I am doing wrong.
EDIT
According to suggestions from T.J.
$('#nav_what-we-do').find('.top-dropdown').find('a').each(function(index, elem) {
//console.log("Descendant: " + elem.tagName + " " + elem.href);
var the_link = elem.href,
hashIndex = the_link.split("#");
if(hashIndex.length == 2) {
console.log(hashIndex);
console.log("Descendant: " + elem.tagName + " " + elem.href);
console.log('First part is: ' + hashIndex[0].indexOf("/what_we_do/"));
}
if (hashIndex.length == 2 && hashIndex[0].indexOf("/what_we_do/") !== -1) {
the_link.attr('href', "#" + hashIndex[1]);
the_link.attr('href', the_link.substring(hashIndex));
the_link.click(function() {
var tab_id = $(this).attr('href');
selectTab(tab_id);
return false;
});
}
});
If I print in console I get:
["http://localhost/testsite/what-we-do/", "solutions"] site_javascript.js:133
Descendant: A http://localhost/testsite/what-we-do/#solutions site_javascript.js:134
First part is: -1 site_javascript.js:135
["http://localhost/testsite/what-we-do/", "features"] site_javascript.js:133
Descendant: A http://localhost/testsite/what-we-do/#features site_javascript.js:134
First part is: -1
Where first part should be the value hashIndex[0].indexOf("/what_we_do/")
What could be going on since hashIndex has the string /what-we-do/?

I think you probably want:
var nav_link;
$('#nav_what-we-do').find('.top-dropdown').find('a').each(function(index, elem) {
console.log("Descendant: " + elem.tagName + " " + elem.href);
var the_link = elem.href,
hashIndex = the_link.indexOf("#");
if (hashIndex !== -1 && the_link.indexOf("/what-we-do/") !== -1) {
the_link.attr('href', the_link.substring(hashIndex));
the_link.click(function() {
var tab_id = $(this).attr('href');
selectTab(tab_id);
return false;
});
}
});
(Note that I declared the_link; if it's already declared somewhere outside the iterator function, you could remove that, but it seems like it should be a local.)
Or alternately (since technically, the above would match if the /what-we-do/ were after the hash):
var nav_link;
$('#nav_what-we-do').find('.top-dropdown').find('a').each(function(index, elem) {
console.log("Descendant: " + elem.tagName + " " + elem.href);
var the_link = elem.href,
split = the_link.split("#");
if (split.length === 2 && split[0].indexOf("/what-we-do/") !== -1) {
the_link.attr('href', "#" + split[1]);
the_link.click(function() {
var tab_id = $(this).attr('href');
selectTab(tab_id);
return false;
});
}
});
There I've limited it so that if there is a hash after the first hash, it's not a match.

This is failing because you're checking an entire, absolute path (http://.....) against just a token of it (/what-we-do/).
There's several ways around this - the easiest is probably to check whether the token you're looking for is IN the URL (rather than is exactly equal to it, as currently).
if (nav_link.indexOf('#') != -1 && nav_link[0].indexOf('/what-we-do/') != -1) {
...

Related

jQuery to emulate iPhone password input changes textbox to disabled in a Visual Studio web application

I am working on a web application in Visual Studio using visual basic and master pages. I have 10 textbox fields on a child page where I would like to emulate the iPhone password entry (ie. show the character entered for a short period of time then change that character to a bullet). This is the definition of one of the text box controls:
<asp:TextBox ID="txtMID01" runat="server" Width="200" MaxLength="9"></asp:TextBox>
At the bottom of the page where the above control is defined, I have the following:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="lib/jQuery.dPassword.js"></script>
<script type="text/javascript">
$(function () {
var textbox01 = $("[id$=txtMID01]");
alert(textbox01.attr("id"));
$("[id$=txtMID01]").dPassword()
});
</script>
When the page loads, the alert displays MainContent_txtMID01 which is the ID of the control preceeded with the name of the content place holder.
The following is the contents of lib/jQuery.dPassword.js (which I found on the internet):
(function ($) {
$.fn.dPassword = function (options) {
var defaults = {
interval: 200,
duration: 3000,
replacement: '%u25CF',
// prefix: 'password_',
prefix: 'MainContent_',
debug: false
}
var opts = $.extend(defaults, options);
var checker = new Array();
var timer = new Array();
$(this).each(function () {
if (opts.debug) console.log('init [' + $(this).attr('id') + ']');
// get original password tag values
var name = $(this).attr('name');
var id = $(this).attr('id');
var cssclass = $(this).attr('class');
var style = $(this).attr('style');
var size = $(this).attr('size');
var maxlength = $(this).attr('maxlength');
var disabled = $(this).attr('disabled');
var tabindex = $(this).attr('tabindex');
var accesskey = $(this).attr('accesskey');
var value = $(this).attr('value');
// set timers
checker.push(id);
timer.push(id);
// hide field
$(this).hide();
// add debug span
if (opts.debug) {
$(this).after('<span id="debug_' + opts.prefix + name + '" style="color: #f00;"></span>');
}
// add new text field
$(this).after(' <input name="' + (opts.prefix + name) + '" ' +
'id="' + (opts.prefix + id) + '" ' +
'type="text" ' +
'value="' + value + '" ' +
(cssclass != '' ? 'class="' + cssclass + '"' : '') +
(style != '' ? 'style="' + style + '"' : '') +
(size != '' ? 'size="' + size + '"' : '') +
(maxlength != -1 ? 'maxlength="' + maxlength + '"' : '') +
// (disabled != '' ? 'disabled="' + disabled + '"' : '') +
(tabindex != '' ? 'tabindex="' + tabindex + '"' : '') +
(accesskey != undefined ? 'accesskey="' + accesskey + '"' : '') +
'autocomplete="off" />');
// change label
$('label[for=' + id + ']').attr('for', opts.prefix + id);
// disable tabindex
$(this).attr('tabindex', '');
// disable accesskey
$(this).attr('accesskey', '');
// bind event
$('#' + opts.prefix + id).bind('focus', function (event) {
if (opts.debug) console.log('event: focus [' + getId($(this).attr('id')) + ']');
clearTimeout(checker[getId($(this).attr('id'))]);
checker[getId($(this).attr('id'))] = setTimeout("check('" + getId($(this).attr('id')) + "', '')", opts.interval);
});
$('#' + opts.prefix + id).bind('blur', function (event) {
if (opts.debug) console.log('event: blur [' + getId($(this).attr('id')) + ']');
clearTimeout(checker[getId($(this).attr('id'))]);
});
setTimeout("check('" + id + "', '', true);", opts.interval);
});
getId = function (id) {
var pattern = opts.prefix + '(.*)';
var regex = new RegExp(pattern);
regex.exec(id);
id = RegExp.$1;
return id;
}
setPassword = function (id, str) {
if (opts.debug) console.log('setPassword: [' + id + ']');
var tmp = '';
for (i = 0; i < str.length; i++) {
if (str.charAt(i) == unescape(opts.replacement)) {
tmp = tmp + $('#' + id).val().charAt(i);
}
else {
tmp = tmp + str.charAt(i);
}
}
$('#' + id).val(tmp);
}
check = function (id, oldValue, initialCall) {
if (opts.debug) console.log('check: [' + id + ']');
var bullets = $('#' + opts.prefix + id).val();
if (oldValue != bullets) {
setPassword(id, bullets);
if (bullets.length > 1) {
var tmp = '';
for (i = 0; i < bullets.length - 1; i++) {
tmp = tmp + unescape(opts.replacement);
}
tmp = tmp + bullets.charAt(bullets.length - 1);
$('#' + opts.prefix + id).val(tmp);
}
else {
}
clearTimeout(timer[id]);
timer[id] = setTimeout("convertLastChar('" + id + "')", opts.duration);
}
if (opts.debug) {
$('#debug_' + opts.prefix + id).text($('#' + id).val());
}
if (!initialCall) {
checker[id] = setTimeout("check('" + id + "', '" + $('#' + opts.prefix + id).val() + "', false)", opts.interval);
}
}
convertLastChar = function (id) {
if ($('#' + opts.prefix + id).val() != '') {
var tmp = '';
for (i = 0; i < $('#' + opts.prefix + id).val().length; i++) {
tmp = tmp + unescape(opts.replacement);
}
$('#' + opts.prefix + id).val(tmp);
}
}
};
})(jQuery);
When I execute my code, the code behind populates the value of the textbox with "123456789" and when the page gets rendered, all the characters have been changed to bullets, which is correct. The problem I am having is that the textbox has been disabled so I can not edit the data in the textbox.
I removed (by commenting out) the references to the disabled attribute but the control still gets rendered as disabled.
As a side note, the code that I found on the internet was originally designed to work with a textbox with a type of password but when I set the TextMode to password, not only does the control get rendered as disabled, but the field gets rendered with no value so I left the TextMode as SingleLine.
Any suggestions or assistance is greatly appreciated.
Thanks!
As far as I know, it is not possible to have it so that while you type a password, the last letter is visible for a second and then turns into a bullet or star.
However what you can do is as the user types in password, with a delay of lets say 500ms store the string the user has typed in so far into some variable and replace the content of the password field or the text field with stars or black bullets. This will give you what you are looking for.

jQuery use dynamically created ID

I am trying to use dynamically created IDs in javascript function, but it's not working. I thought that prepending # to string id should work, but it's not.
Code:
var IterateCheckedDatesAndUncheckWithSameValue = function (elementNumber) {
idCheckBoxToCompare = "CMP_KD1_tcDE_tctpDNDR_chkDNDRDay" + elementNumber.toString();
if ($("'#" + idCheckBoxToCompare + "'").prop('checked') === false) {
return;
}
textBoxID = "CMP_KD1_tcDE_tctpDNDR_txtDNDRDay" + elementNumber.toString();
textBoxValue = $("'#" + textBoxID + "'").val();
for (i = 1; i < 8; i++) {
if (i !== elementNumber) {
idCheckBox = "CMP_KD1_tcDE_tctpDNDR_chkDNDRDay" + i.toString();
idInputBox = "CMP_KD1_tcDE_tctpDNDR_txtDNDRDay" + i.toString();
inputBoxValue = $("'#" + idInputBox + "'").val();
if ($("'#" + idCheckBox + "'").prop('checked') === true) {
if (inputBoxValue === textBoxValue) {
$("'#" + idCheckBox + "'").prop('checked', false);
}
}
}
}
}
I've tried to build same id as this is:
'#testid'
so usage would be:
$('#testid')
But it's not working. How to use properly dynamically created IDs?
Your code is look complicated with too many " and '. Also Javascript can concat string and number by just use +. No need to convert it to string first. So, I updated it to make it more readable.
Try this
var IterateCheckedDatesAndUncheckWithSameValue = function(elementNumber) {
idCheckBoxToCompare = "CMP_KD1_tcDE_tctpDNDR_chkDNDRDay" + elementNumber;
if ($('#' + idCheckBoxToCompare).prop('checked') === false) {
return;
}
textBoxID = "CMP_KD1_tcDE_tctpDNDR_txtDNDRDay" + elementNumber;
textBoxValue = $('#' + textBoxID).val();
for (i = 1; i < 8; i++) {
if (i !== elementNumber) {
idCheckBox = "CMP_KD1_tcDE_tctpDNDR_chkDNDRDay" + i;
idInputBox = "CMP_KD1_tcDE_tctpDNDR_txtDNDRDay" + i;
inputBoxValue = $('#' + idInputBox).val();
if ($('#' + idCheckBox).prop('checked') === true) {
if (inputBoxValue === textBoxValue) {
$('#' + idCheckBox).prop('checked', false);
}
}
console.log('#' + idCheckBox); //print here just to see the id results
}
}
}
ID in html can be only one element per page. So please make sure that the ID you generate from this method not match with other.
Jquery selector can read String variable.
So you can just do var id = "#test". Then put it like this $(id).
Or
var id = "test"; then $("#"+test).
Use this,
var IterateCheckedDatesAndUncheckWithSameValue = function (elementNumber) {
idCheckBoxToCompare = "CMP_KD1_tcDE_tctpDNDR_chkDNDRDay" + elementNumber.toString();
if ($("#" + idCheckBoxToCompare).prop('checked') === false) {
return;
}
textBoxID = "CMP_KD1_tcDE_tctpDNDR_txtDNDRDay" + elementNumber.toString();
textBoxValue = $("#" + textBoxID).val();
for (i = 1; i < 8; i++) {
if (i !== elementNumber) {
idCheckBox = "CMP_KD1_tcDE_tctpDNDR_chkDNDRDay" + i.toString();
idInputBox = "CMP_KD1_tcDE_tctpDNDR_txtDNDRDay" + i.toString();
inputBoxValue = $("#" + idInputBox).val();
if ($("#" + idCheckBox).prop('checked') === true) {
if (inputBoxValue === textBoxValue) {
$("#" + idCheckBox).prop('checked', false);
}
}
}
}
}
I face the same problem using Jquery .Try $(document).getElementbyId('myid'). Hope help.
Edit
Change :
$("#" + idCheckBoxToCompare) by $(document).getElementbyId(idCheckBoxToCompare)

open textfield after click on span does not work

I am not able to create an edit in place feature with JavaScript/ jQuery. I could not use the plugin editinplace, because I need to put a datepicker on it. My code below does not work for some strange reason:
function editImpfDatumImpfung1Clicked(sender)
{
var sText = $(this).text();
var sId = $(this).attr("id");
$(this).attr("id", "tobechanged");
$(this).after('<input type="text" id="' + sId + '" value="' + sText + '" />');
$(this).remove();
bImpfung1Clicked = true;
$("#" + sId).focus();
$("#" + sId).datepicker(datepickerOptions);
if (bFirstRegisterImpfung1 === true)
{
firstRegisterImpfung1();
bFirstRegisterImpfung1 = false;
}
}
$(document).ready(function()
{
$elem = $("span[id^='impfung_1['");
if ($elem.length > 0)
{
bFirstRegisterImpfung1 = true;
$elem.click(editImpfDatumImpfung1Clicked);
}
});
Edit:
No Errors in console.
console.log($("#" + sId).val()); causes undefined
Edit 2:
Just needed to escape the id like this:
sId = sId.replace(/[[]/g,'\\[');
sId = "#" + sId.replace(/]/g,'\\]');
Thanks for your advice.
I imagine you have a typo in the following line:
$elem = $("span[id^='impfung_1['");
try this instead:
$elem = $("span[id^='impfung_1']");

Regex match returns null for no reason

i am making a client for my node.js irc bot and want to implement tab complete but the regex in the following code returns null for no reason. i have included what's logged as comments next to the console.log statement.
what is tab complete: i type "mic" and press tab, it the automatically completes it to "michael" because he is a user in the channel.
tabStart = false;
$("#textbox").keydown(function (e) {
if (!$(this).val().length) return;
if (e.keyCode === 9) {
e.preventDefault();
var text = $(this).val();
console.log('text: ' + text);// mic
var index = text.lastIndexOf(" ");
console.log('index: ' + index);// -1
if (!tabStart) {
tabStart = index > -1 ? text.substr(index + 1) : text;
var current = '';
} else {
var current = index > -1 ? text.substr(index + 1) : text;
}
console.log('tabStart: ' + tabStart);// mic
console.log('current: ' + current);//
var active = $("#tabs").tabs("option", "active");
var channel = $("#tabs ul>li a").eq(active).attr("href");
console.log('channel: ' + channel);// #debug
var users = $(channel + " .user-list li");
var regex = new RegExp("^" + tabStart + ".*", "i");
console.log('regex: ' + regex);// /^mic.*/i
for (var i = 0; i < users.length; ++i) {
var user = $(users[i]).text();
console.log('user: ' + user);// michael
var match = user.match(regex);
console.log('match: ' + match);// null
if (match) {
var newText = (index > -1 ? text.substr(0, index + 1) : "") + user;
console.log('newText: ' + newText);
$(this).val(newText);
break;
}
}
} else {
tabStart = false;
}
});
as i said, i can't seem to find an explanation for this because i tried the following in the javascript console and it works
var regex = new RegExp("^mic.*", "i");"michael".match(regex);
It looks like you have an issue with getting the correct text from users. Since I don't know your actual HTML, I created a CodePen and commented out some of the channel lines and added users as a typical array. Doing that, your regex works fine.
Here is the codePen in action.
figured out the problem. user was wrapped in ​.

Need help to figure out why current code does not work with current latest (1.6.4) version of JQuery

Below is the code, the program is split into two main segments.
One that performs operation on each Select element and the other
on all the option elements within this\each select and this one
does not work as it should append a price "[+$00]" to each select option text value,
bar the currently selected one. The piece of code that does not work is tagged.
Worked fine with 1.5.1, 1.5.2 and does not work with all starting from 1.6
// ===== CODE DOES NOT WORK FROM HERE WITH 1.6.4============
$(this).find('option').each(function () {
//$(this).append('<span></span>');
var uov = parseInt($(this).attr('value')) || 0; //Unselected option value
var uop; //Unselected Option Price
for (d = 0; d <= data.length; d++) {
if (data[d].partid == uov) {
uop = data[d].price;
break;
}
}
//debugger;
var pricediff = Math.abs(uop - sop);
var xtext = $(this).text();
if (xtext.match(/\✔/) != null) {
var temp = xtext.replace(/✔/g, '');
xtext = temp;
}
if (xtext.match(/\[.*\]/) != null) {
var temp = xtext.split('[')[0];
var temp2 = xtext.split(']')[1];
xtext = temp2;
}
if (uov != 0) {
if (pricediff != 0) {
var diff = '[' + (sop > uop ? '-' : '+') + '$' + pricediff + ']';
$(this).attr("text", diff + " " + xtext);
}
else {
$(this).attr("text", " ✔ " + " " + xtext);
}
}
//=============== TO HERE ========================
Don't use:
$(this).attr('value')
to get the value of a form field. Use:
$(this).val()
This has caused many headaches with our client developers when we changed our framework's jQuery version.
--- Edit ---
You most certainly should not be trying to edit the text of an element with the attr() function as you have here:
$(this).attr("text", diff + " " + xtext);
You should use:
$(this).text(diff + " " + xtext);

Categories

Resources