HTML code in Javascript fails - javascript

I need to add an HTML anchor in my code. The fist code works fine but does not include the anchor tag that I need. But the second one fails:
This works fine, does not include :
<script type='text/javascript'>//<![CDATA[
$('#Quantity').keyup(function () {
var textualValue = $(this).val();
var numericValue = parseInt(textualValue, 10);
if (!isNaN(numericValue)) {
modifyDOMWithNumber(numericValue);
} else {
modifyDOMWithNumber(0);
}
});
function modifyDOMWithNumber(number) {
var ul = $('ul#ListToAlter').empty();
var item;
for (var i = 1; i <= number; i++) {
item = $("<li>");
if (i == 1) {
item.text("Options for your 1st $Name");
}else if(i == 2) {
item.text("Options for your 2nd $Name");
}else if(i == 3) {
item.text("Options for your 3rd $Name");
} else {
item.text("Options for your number " + i + "th $Name");
}
ul.append(item);
}
}
//]]>
</script>
This fails, does include :
<script type='text/javascript'>//<![CDATA[
$('#Quantity').keyup(function () {
var textualValue = $(this).val();
var numericValue = parseInt(textualValue, 10);
if (!isNaN(numericValue)) {
modifyDOMWithNumber(numericValue);
} else {
modifyDOMWithNumber(0);
}
});
function modifyDOMWithNumber(number) {
var ul = $('ul#ListToAlter').empty();
var item;
for (var i = 1; i <= number; i++) {
item = $("<li>");
if (i == 1) {
item.html("<a>Options for your 1st $Name</a>");
}else if(i == 2) {
item.html("<a>Options for your 2nd $Name</a>");
}else if(i == 3) {
item.html("<a>Options for your 3rd $Name</a>");
} else {
item.html("<a>Options for your number " + i + "th $Name</a>");
}
ul.append(item);
}
}
//]]>
</script>

Use
item.html("<a> what ever html text</a>")
instead of
item.text("<a> xxxx </a>").
Also note that in the code that fails, the for loop is missing, so i won't be defined.

The second piece of code, using item.html("<a>Options for your 1st $Name</a>"); probably works fine. But you are not inclusing an href attribute for the <a> element, which causes some browsers to not decorate the text as a link. In order for it to be decorated as a link (underline, characteristic color etc), you could replace it with:
item.html("Options for your 1st $Name");
See, also, this short demo.

Related

How to edit CSS of a JavaScript variable in JS?

I have a live search for a website and it's working just fine but I cannot seem to figure out how to highlight the search term in the result. Below is my JS code. I assume I need to edit the data-search-term variable but I am clueless about how to go about it.
I know only HTML/CSS. No JavaScript.
jQuery(document).ready(function($) {
$('.training-search-list li').each(function() {
$(this).attr('data-search-term', $(this).text().toLowerCase());
});
$('.training-search-box').on('keyup', function() {
var searchTerm = $(this).val().toLowerCase();
$('.training-search-list li').each(function() {
if ($(this).filter('[data-search-term *= ' + searchTerm + ']').length > 0 || searchTerm.length < 1) {
$(this).show();
} else {
$(this).hide();
}
});
});
});
Thanks in advance.
I made it long time ago
(function($){
$('#categoryFilter').focus().keyup(function(event){
var input = $(this);
var val = input.val();
if(val == ''){
$('#filter li').show();
$('#filter a span').removeClass('highlighted');
return true;
}
var regexp = '\\b(.*)';
for (var i in val) {
regexp += '('+val[i]+')(.*)';
}
regexp += '\\b';
$('#filter li').show();
$('#filter').find('a > span').each(function(){
var span = $(this);
var resultats = span.text().match(new RegExp(regexp,'i'));
if(resultats){
var string = '';
for (var i in resultats){
if(i > 0){
if(i%2 == 0){
string += '<span class="highlighted">'+resultats[i]+'</span>';
}else {
string += resultats[i];
}
}
}
span.empty().append(string);
}else {
span.parent().parent().hide();
}
});
});
})(jQuery);
Maybe you can try to make your own code with some part of mine

Need to check and alert duplicate value in an array

I can see the array in console but can not check them if there are same values in it.
$('.tab2field').each(function () {
PackageName.push($('.span2', this).val() );
PackageCount.push($('.ex > :selected', this).text())
});
This is what i am trying to do.
for (var i = 0; i <PackageName.length; i++) {
if (PackageName[i] != current) {
if (cnt > 0) {
}
current = PackageName;
cnt = 1;
} else {
cnt++;
}
}
if (cnt > 1) {
alert(' Check multiple inputs');
}
You can do checking before pushing:
$('.tab2field').each(function () {
var name = $('.span2', this).val();
if (PackageName.indexOf(name) === -1) {
PackageName.push(name);
PackageCount.push($('.ex > :selected', this).text())
} else {
console.warn('Package ' + name + ' is already included');
}
});
But I am not sure whether this is what you wanted to achieve becuase your question is a bit unclear

Is this text snipper mini-plugin of mine efficient?

I am working on creating a WordPress plugin to snip overflowing multiline text and add "...". It's pretty basic for now, but I am using some for loops and am just wondering if this is the most efficient way to go about doing this without clogging resources.
(function($) {
//Praveen Prasad "HasScrollBar" function adapted http://stackoverflow.com/questions/7341865/checking-if-jquery-is-loaded-using-javascript
$.fn.hasOverflow = function() {
var elm = $(this);
var hasOverflow = false;
if ( elm.clientHeight < elm.scrollHeight ) {
hasOverflow = true;
}
return hasOverflow;
}
//http://www.mail-archive.com/discuss#jquery.com/msg04261.html
jQuery.fn.reverse = [].reverse;
$(document).ready( function() {
if ( $('.' + snipClass).length > 0 ) {
var count = 0;
for (var i = 0; i < 10000; i++) {
$('.' + snipClass).each( function () {
var el = this;
//Check for overflows
if ( el.clientHeight < el.scrollHeight) {
if ($(this).children().length > 0) { //Handle child elements
$("> *", this).reverse().each( function () {
for (var j = 0; j < 10000; j++) {
if ( $(this).text() != "" && el.clientHeight < el.scrollHeight ) {
$(this).text($(this).text().substring(0,$(this).text().length - 1));
} else {
break;
}
}
});
} else { //Handle elements with no children
$(this).text($(this).text().substring(0,$(this).text().length - 1));
}
} else { //Add '...'
count++;
}
});
//Add ... once finished
if ( count >= $('.' + snipClass).length) {
$('.' + snipClass).each( function () {
var el = this;
if ($(this).children().length > 0) { //Handle child elements
$("> *", this).reverse().each( function () {
if ( $(this).text() != "" ) {
$(this).text($(this).text().substring(0, $(this).text().length - 3) + "...");
}
});
} else { //Handle elements with no children
$(this).text($(this).text().substring(0, $(this).text().length - 3) + "...");
}
});
break;
}
}
}
});
}(jQuery));
Brief explanation: "snipClass" is the value from the textfield in the plugin's settings page. If the element in question has a wrapper that is say 200px, but its text overflows it, I keep trimming text letter by letter until it doesn't overflow anymore. I opted to go with for loops rather than intervals, because even with 1s intervals, you could see the text getting removed letter by letter, and it's much faster with the for loop. If the wrapper has any direct children (maybe a tag with elements), my plugin goes in reverse order to snip text from them until there is no overflow.

textbox value with hard coded dash

I have a textbox in the page. <input type="text" id="cell">
I have used below jquery....
i = 0;
$(document).ready(function () {
$("#cell").keypress(function () {
i += 1;
if (i == 4) {
var cellValue = $("#cell").val() + "-";
$("#cell").val(cellValue);
}
});
});
whenever an user types 12345678 (or any number) it automatically shows 123-45678. But problem is when user uses backspace or delete and then starts typing 12345678 it does not show 123-45678. Please help
i should be the length of the value , not the number of times you pressed the key
Try this -
$("#cell").keypress(function () {
i = $(this).val().length;
if (i == 3) {
var cellValue = $("#cell").val() + "-";
$("#cell").val(cellValue);
}
});
Demo --> http://jsfiddle.net/KZmc9/2/
Try
$(document).ready(function(){
$("#cell").keypress(function(){
if (this.value.length == 3) {
$("#cell").val(this.value + "-");
}
});
});
Demo: Fiddle
I would split the input into two, because otherwise users have to delete the dash if they want to delete the 3rd number.
http://jsfiddle.net/TATnK/
$(document).ready(function() {
$('#cell_1').on('input', function(e) {
if($(this).val().length == 3) {
$('#cell_2').focus();
}
});
$('#cell_2').keyup(function(e) {
if(e.which == 8 && $(this).val().length == 0) {
$('#cell_1').focus();
}
});
});

jQuery limit "Dropdown Check List" selects

I'm using jquery with dropdownchecklist item.
this is my code to config selectbox.
jQuery('#selectbox').dropdownchecklist({ width: 120, maxDropHeight: 100, firstItemChecksAll: false, emptyText: 'Select' });
I want to limit the select for only 2 selects.
If the user select 2 options all others item will disable for selecting.
How can I do it?
Update:
I found the easiest way to do this
function Selectbox_limit(jidList) {
var jids = '';
var counter = 0;
for(var i=0; i<jidList.options.length; i++) {
if(jidList.options[i].selected == true)
counter++;
if(counter >= 2) {
jidList.options[i-1].selected = false;
jQuery("#selectbox").dropdownchecklist("destroy");
jQuery("#selectbox option").attr('disabled','disabled');
jQuery("#selectbox option:selected").attr("disabled","");
jQuery('#selectbox').dropdownchecklist({ _propeties_ });
return;
} else if(counter < 2) {
jQuery("#selectbox").dropdownchecklist("destroy");
jQuery("#selectbox option").attr("disabled","");
jQuery('#selectbox').dropdownchecklist({ _propeties_ });
return;
}
}
The dropdownchecklist add the class active to the check boxes so you can use it like this:
$('.active').change(function () {
var num = 0;
$('.active:checked').each(function () {
num++;
});
if(num >= 2)
{
$('.active:checked').attr("disabled", "disabled");
$('.active:checked').each(function () {
$(this).removeAttr();
});
}
else
{
$('.active').removeAttr("disabled", "disabled");
}
});
here is a sample of a jQuery Dropdown Check List with limit
onItemClick: function(checkbox, selector){
var justChecked = checkbox.prop("checked");
var checkCount = (justChecked) ? 1 : -1;
for( i = 0; i < selector.options.length; i++ ){
if ( selector.options[i].selected ) checkCount += 1;
}
if ( checkCount > 3 ) {
alert( "Limit is 3" );
throw "too many";
}
}
You can do it by this
var $b = $('input[type=checkbox]');
if(($b.filter(':checked').length)>2){
$b.attr("disabled", true);
}
or you can use
$(':checkbox:checked").length
$(":checkbox").filter(':checked').length
hope it help.

Categories

Resources