jQuery if condition text contains - javascript

I wrote a simple if condition, but not quite working.
if text is 123 change to hi, if text is 456 change it to hi2
Could someone please give me a hand.
<h1>123</h1>
<h1>456</h1>
<h1>789</h1>​
$(document).ready(function() {
var changeText1 = '123';
var changeText2 = '456';
var text = $(h1).text();
if (text == changeText) {
$(this).text('hi');
} else if (text == changeText2 ) {
$(this).text('hi2');
}
});
​
http://jsfiddle.net/8P2ma/

There are multiple things wrong with your code:
$(document).ready(function() {
var changeText1 = '123';
var changeText2 = '456';
var text = $(h1).text(); //aside from having to iterate through, the jquery
//selector needs to be enclosed in quotes: $('h1')
if (text == changeText) { //The variable 'changeText' does not exist.
$(this).text('hi');
} else if (text == changeText2 ) {
$(this).text('hi2');
}
});
//working code:
$(document).ready(function() {
var changeText1 = '123';
var changeText2 = '456';
$('h1').each(function() {
var text = $(this).text();
if (text == changeText1) {
$(this).text('hi');
} else if (text == changeText2) {
$(this).text('hi2');
}
});
});​

$(function() {
$('h1:contains("123")').text('hi');
$('h1:contains("456")').text('hi2');
});​
FIDDLE

Do it like this:
$(document).ready(function() {
var change = {
'123': 'hi',
'456': 'hi2'
};
$('h1').text(function(i, txt) {
return change[$.trim(txt)];
});
});
DEMO: http://jsfiddle.net/By4Ra/

Related

How to display default message when no results found on Jquery search filter

I'm currently building a page where a search field acts as a filter. It works perfectly fine and shows data against related word, but there is one issue that I'd like to solve. When the entered string or other words is not found in all the existing the page remains blank.
How could I display a default message on my page when no results are found by the filter? Something like a simple <p> explaining that no results were found.
The idea is to display it only once as long as the string is not found.
$('#search_field').on('keyup', function() {
var value = $(this).val();
var patt = new RegExp(value, "i");
$('#userFind').find('tr').each(function() {
var $table = $(this);
if (!($table.find('td').text().search(patt) >= 0)) {
$table.not('.t_head').hide();
}
if (($table.find('td').text().search(patt) >= 0)) {
$(this).show();
}
});
});
This is untested since you haven't provided any table to your question.
After you have looped though all tr, then check if any is visible. If not then append a tr with custom message and remove it and new search.
$('#search_field').on('keyup', function() {
var value = $(this).val();
// console.log(value);
var patt = new RegExp(value, "i");
$(".noRecord").remove();
$('#userFind').find('tr').each(function() {
var $table = $(this);
if (!($table.find('td').text().search(patt) >= 0)) {
$table.not('.t_head').hide();
} else {
$(this).show();
}
});
if ($('#userFind tr:visible').length == 0) {
$('#userFind tbody').append("<tr class='noRecord'><td>No records found.</td></tr>")
}
});
Assuming you have a div:
<div id="zeroHits">no results were found</div>
You can hide/show the #zeroHits div as follows:
$('#search_field').on('keyup', function() {
var value = $(this).val();
var patt = new RegExp(value, "i");
var zeroHits = true;
$('#userFind').find('tr').each(function() {
var $table = $(this);
if (!($table.find('td').text().search(patt) >= 0)) {
$table.not('.t_head').hide();
}
if (($table.find('td').text().search(patt) >= 0)) {
$(this).show();
zeroHits = false;
}
});
if(zeroHits) {
$('#zeroHits').show();
} else {
$('#zeroHits').hide();
}
});
Try this untested code
post your HTML and I can test
const $rows = $('#userFind tbody tr'); // only tbody rows
$('#search_field').on('keyup', function() {
var value = $(this).val();
// console.log(value);
var patt = new RegExp(value, "i");
$rows.each(function() {
const found = $(this).find('td').filter(function() {
return $(this).text().search(patt) != -1
}).length > 0
$(this).toggle(found);
});
$("#notFound").toggle($rows.filter(":visible").length === 0)
});

How to Convert serializedObject to UL (unordered list)?

Anyone knows how to convert the output from this code into an unordered list?
$.fn.serializeObject = function()
{
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name] !== undefined) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
$(function() {
$('form').submit(function() {
$('#result').text(JSON.stringify($('form').serializeObject()));
return false;
});
});
The code above outputs for example like this:
{"costPerDay":"20","numberOfDays":"20","designCost":"40","cmsIntegration":"64","seoContentStrategy":"75"}
I was hoping if there's a way to make it output into an unordered list?
I guess the code you made does not work, maybe this will help you better figure out what i am aiming for, attached is the full code that I wanted the output as "Unordered List" and the source in CodePen http://jsfiddle.net/JOEHOELLER/217m94fk/2/ If you want to check out the working Range Slider. Thanks
function proRangeSlider(sliderid, outputid, colorclass) {
var x = document.getElementById(sliderid).value;
document.getElementById(outputid).innerHTML = x;
document.getElementById(sliderid).setAttribute('class', colorclass);
updateTotal();
}
var total = 0;
function updateTotal() {
var list= document.getElementsByClassName("range");
[].forEach.call(list, function(el) {
console.log(el.value);
total += parseInt(el.value);
});
document.getElementById("n_total").innerHTML = total;
}
$.fn.serializeObject = function()
{
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name] !== undefined) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
$(function() {
$('form').submit(function() {
$('#result').text(JSON.stringify($('form').serializeObject()));
return false;
});
});
I'm not sure how your desired result is supposed to look like, but either way you can just iterate over your object:
// let obj = JSON.stringify($('form').serializeObject())
let obj = {"costPerDay":"20","numberOfDays":"20","designCost":"40","cmsIntegration":"64","seoContentStrategy":"75"};
$("#result").empty().append("<ul></ul>");
for (const entry in obj){
$("#result > ul").append(`<li>${entry}: ${obj[entry]}</li>`);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="result"></div>
Or if you prefer a single-liner:
$("#result").empty().append(
"<ul>" + Object.entries(obj).map(e => `<li>${e[0]}: ${e[1]}`).join("") + "</ul>"
);
Working demo:
http://jsfiddle.net/7a5xjwbh/

Any better way to declare variables avoiding repetition of code?

Here is the js code which i am trying to use. I don't like the same code repeating again and I couldn't help myself to do this in a better way.
$(function(){
$('[data-behavior~=quick-reject]').on("click", function(){
var form = $(this).closest("[data-behavior~=modal-footer]").find("form");
var some_action = form.find("#some_actions").val();
var some_reasons = form.find("[data-behavior~=escalation-reason-select-box]");
if((some_reasons.val() === "") && ( some_action === "reject")){
var errorReason = "Please select a reason";
form.addClass("error").
parent().
find("div.error").
html(errorReason);
}else{
form.submit();
}
});
$(document).on("change", "#some_actions", function (){
var form = $(this).closest("[data-behavior~=modal-footer]").find("form");
var some_action = form.find("#some_actions").val();
var some_reasons = form.find("[data-behavior~=escalation-reason-select-box]");
if(some_action === "verify"){
some_reasons.hide();
}else{
some_reasons.show();
}
});
});
You could just make a little utility function, something like.
function getVars(that) {
var form = $(that).closest("[data-behavior~=modal-footer]").find("form");
return {
form: form,
some_action: form.find("#some_actions").val(),
some_reasons: form.find("[data-behavior~=escalation-reason-select-box]")
}
}
$('[data-behavior~=quick-reject]').on("click", function(){
var v = getVars(this);
if((v.some_reasons.val() === "") && ( v.some_action === "reject")){
var errorReason = "Please select a reason";
v.form.addClass("error").
parent().
find("div.error").
html(errorReason);
}else{
v.form.submit();
}
});
$(document).on("change", "#some_actions", function (){
var v = getVars(this);
if(v.some_action === "verify"){
v.some_reasons.hide();
}else{
v.some_reasons.show();
}
});

jQuery / js toLowercase

I can't turn searchBox to a .toLowerCase and my code is case sensitive because of this. I want the code to scan on both upperCase and lowerCase letters.
I wasn't able to find a solution to my problem.
<script>
$("#searchBtn").keyup(function () {
var searchBox = $("#searchBtn").val();
var returnRows = [];
$('tr').not('.headerRow').each(function () {
var addRow = true;
var $currentRow = $(this);
$currentRow.find('td').each(function () {
var $td = $(this);
var word = $td.text();
if (word.indexOf(searchBox) > -1) {
addRow = false;
return false;
// console.log("KOMT IN IF STATEMENT"); //sla deze rij op in een tijdelijke array
}
});
if (addRow) {
returnRows.push($currentRow)
}
});
if (true)
{
$('tr').show();
}
$.each(returnRows, function (i, v) {
$(v).hide();
});
});
</script>
I am not sure but you are making it a bit more complicated. Try something like this:
$("#searchBtn").keyup(function() {
var word = $("#searchBtn").val(),
timer;
if(timer){ clearTimeout(timer); }
timer = setTimeout(function(){
$('tr').not('.headerRow').filter(function(){
var txt = $(this).find('td').text();
return txt.indexOf(word) !== -1 && txt === word;
}).hide();
},900);
});
=== lets you compare strictly. So, in such case T !== t would result in true.

How do I hide an image only within a list item via ID?

I have a list item:
<li id="optionCarousel" onclick="toggleTick(this)"><a><img class="tick" id="optionCarousel_Tick" src="/images/tick.png">Carousel</a></li>
When I call my method:
function toggleTick(element) {
var elementText = element.id += "_Tick";
var tickElement = $g(elementText);
if (tickElement != null) {
if (tickElement.style.visibility == "visible") {
tickElement.style.visibility = "hidden";
}
else {
tickElement.style.visibility = "hidden";
}
}
}
It hides the entire list item and not just the image which I have passed. Any ideas on how I can hide the image only?
Fiddle HERE
Try
function toggleTick(element) {
var elementText = element.id += "_Tick";
var tickElement = $g(elementText);
tickElement.toggle()
}
do something like this:
function toggleTick(element) {
var elementText = element.id += "_Tick";
var tickElement = document.getElementById(elementText );
if (tickElement != null) {
if (tickElement.style.visibility == "visible") {
tickElement.style.visibility = "hidden";
}
else {
tickElement.style.visibility = "hidden";
}
}
}
Try this, this will be help you
$('#optionCarousel').click(function () {
var tickElement = '#' +$(this).prop('id')+'_Tick';
$(tickElement).slideToggle();
});
Fiddle Here

Categories

Resources