Reputation: 97
I want to change the text inside a link with jQuery when the href attribute is undefined. Here is my code;
<input type="text" id="sample"/><button id="button">submit</button>
<table id="table" border="1">
<tr>
<td>less than 50</td>
<td>less than 100</td>
<td>less than 500</td>
<td>less than 1000</td>
<td>more than 1000</td>
</tr>
</table>
js:
$("#button").click(function()
{
var val=$("#sample").val();//alert(val)
if(val<50){
var col1=val;
}else if(val<100){
var col2=val;
}else if(val<500){
var col3=val;
}else if(val<1000){
var col4=val;
}else if(val>1000){
var col5=val;
}
var row='<tr>'+
'<td><a href="#">'+col1+'</a></td>'+
'<td><a href="#">'+col2+'</a></td>'+
'<td><a href="#">'+col3+'</a></td>'+
'<td><a href="#">'+col4+'</a></td>'+
'<td><a href="#">'+col5+'</a></td>'
$("#table tr:last").after(row);
$("#table").each(function(){
if ($(this).attr('href') == undefined){
var href=$(this).attr('href');
$(href).text("");
}
});
}
);
I need all undefined href text() to null or 0.I used like this.,
$("#table").each(function(){
if($(this).attr('href') == undefined){
var href=$(this).attr('href');
$(href).text("");
}
});
But it doesn't worked. Sql Fiddle:http://jsfiddle.net/2ok5mzx9/
Upvotes: 0
Views: 53
Reputation: 24276
I would definitely change your script with this one:
$("#button").click(function() {
$('#table').append('<tr><td></td><td></td><td></td><td></td><td></td></tr>');
var range = new Array(Number.NEGATIVE_INFINITY, 50, 100, 500, 1000, Number.POSITIVE_INFINITY);
for (var i = 0; i < range.length; i++) {
if ($('#sample').val() > range[i + 1] || $('#sample').val() < range[i]) {
continue;
}
$('#table tr:last td:eq(' + i + ')').html('<a href="#">' + $('#sample').val() + '</a>');
break;
}
});
HERE is the working example..
Upvotes: 0
Reputation: 31749
Define them as 0
.
var col1 = 0;
col2 = 0;
col3 = 0;
col4 = 0;
col5 = 0;
if (val < 50) {
col1 = val;
} else if (val < 100) {
col2 = val;
} else if (val < 500) {
col3 = val;
} else if (val < 1000) {
col4 = val;
} else if (val > 1000) {
col5 = val;
}
Upvotes: 2
Reputation: 87233
You are not checking the href
as #
.
$("#table a").each(function () {
if ($(this).attr('href') == undefined || $(this).attr('href') == '#') {
$(this).text("");
}
});
Demo: https://jsfiddle.net/tusharj/2ok5mzx9/1/
Upvotes: 1