Javascript creating json object from two strings - javascript

So I will start with my needs. I have a task to create json output using nightwatch.js from the ul list where inside lists are few div elements with classes like name, surname... But really I can't think of any of solutions. Here is my html
<html>
<meta charset="utf-8">
<body>
<ul class="random">
<li class="list">
<div class="name">John</div>
<div class="surname">Lewis</div>
</li>
<li class="list odd">
<div class="name">Nick</div>
<div class="surname">Kyrgios</div>
</li>
</ul>
</body>
</html>
And here is my nightwatch.js script
'Test' : function(browser) {
function iterate(elements) {
elements.value.forEach(function(el) {
browser.elementIdText(el.ELEMENT, function(r) {
browser.elementIdAttribute(el.ELEMENT, 'class', function(att){
// output for json i guess
console.log(att.value + ' => ' + r.value)
})
});
});
}
browser
.url('http://url.com/nightwatch.php')
.waitForElementVisible('body', 8000)
.elements('css selector', 'ul li div', iterate)
.end();
}
Basically this will execute the following:
name => John
surname => Lewis
name => Nick
surname => Kyrgios
Output is a string for both...
And how can I make it like
[{name: "John", surname: "Lewis"}, {name: "Nick", surname: "Kyrgios"}]

This should work. You just need to keep track of the object and place it inside the array after list.
function iterate(elements) {
var objArr = [];
var obj = {};
elements.value.forEach(function(el, idx) {
browser.elementIdText(el.ELEMENT, function(r) {
browser.elementIdAttribute(el.ELEMENT, 'class', function(att){
if (obj.hasOwnProperty(att.value)) {
objArr.push(obj);
obj = {};
}
obj[att.value] = r.value;
});
});
if (idx === (elements.value.length-1)) {
objArr.push(obj);
console.log(objArr);
}
});
}

As with Will's solution, I used straight JavaScript. It does not appear that the nightwatch.js code for this provides any significant benefit. In addition, your question does not specify that only nightwatch.js should be used.
As opposed to Will, I have assumed that the class on your inner <div> elements could be arbitrary and that the arbitrary class should be used as the key/property on the object for that entry. Choosing to use this method vs. restricting it only to a name or surname property will depend on what your HTML really is, and how you want to handle classes which are not those two strings.
var theList = [];
var listItems = document.querySelectorAll('li');
for (var itemIndex=0,itemLength=listItems.length; itemIndex < itemLength; itemIndex++) {
var entry = {};
divs = listItems[itemIndex].querySelectorAll('div');
for (var divsIndex=0, divsLength=divs.length; divsIndex < divsLength; divsIndex++) {
entry[divs[divsIndex].className] = divs[divsIndex].textContent;
}
theList.push(entry);
}
outputJson = JSON.stringify(theList);
console.log(outputJson);
<html>
<meta charset="utf-8">
<body>
<ul class="random">
<li class="list">
<div class="name">John</div>
<div class="surname">Lewis</div>
</li>
<li class="list odd">
<div class="name">Nick</div>
<div class="surname">Kyrgios</div>
</li>
</ul>
</body>
</html>

What about something like this?
function iterate(elements) {
var jsonArray = [];
var jsonBuffer = "";
elements.value.forEach(function(el) {
browser.elementIdText(el.ELEMENT, function(r) {
browser.elementIdAttribute(el.ELEMENT, 'class', function(att){
// output for json i guess
if (att.value == 'name') {
jsonBuffer += "{" + att.value + ":" + "" + r.value + "" + ",";
}
else {
jsonBuffer += att.value + ":" + "" + r.value + "" + "}";
jsonArray.push(jsonBuffer);
jsonBuffer = "";
}
})
});
});
var jsonOutput = "[";
var i = 0;
jsonArray.forEach(function(el) {
if (i < jsonArray.length) {
jsonOutput += el + ",";
} else {
jsonOutput += el + "]";
}
i++;
}
}

I'm not familiar with Nightwatch, but you essentially loop through the elements and push them on to an array.
var results = [];
var entries = document.querySelectorAll('li');
for (var ix = 0; ix < entries.length; ix++) {
var name = entries[ix].querySelector('.name').innerText;
var surname = entries[ix].querySelector('.surname').innerText;
results.push({
name: name,
surname: surname
});
}
console.log(results);
<ul class="random">
<li class="list">
<div class="name">John</div>
<div class="surname">Lewis</div>
</li>
<li class="list odd">
<div class="name">Nick</div>
<div class="surname">Kyrgios</div>
</li>
</ul>

Related

How to bold searched content using only javascript?

I'm trying to make an auto suggest search using javascript. All things are working fine, now i wanted to make searched text bold in the list.
Is this possible when user search something then only search text become bold in the result list. For example if i search one then one will be bold in the list.
var inputId = 'filter-search';
var itemsData = 'filter-value';
var displaySet = false;
var displayArr = [];
function getDisplayType(element) {
var elementStyle = element.currentStyle || window.getComputedStyle(element, "");
return elementStyle.display;
}
document.getElementById(inputId).onkeyup = function() {
var searchVal = this.value.toLowerCase();
var filterItems = document.querySelectorAll('[' + itemsData + ']');
for(var i = 0; i < filterItems.length; i++) {
if (!displaySet) {
displayArr.push(getDisplayType(filterItems[i]));
}
filterItems[i].style.display = 'none';
if(filterItems[i].getAttribute('filter-value').toUpperCase().indexOf(searchVal.toUpperCase()) >= 0) {
filterItems[i].style.display = displayArr[i];
}
}
displaySet = true;
}
<input type="text" id="filter-search" />
<ul>
<li filter-value="One Is">One Is (Uppercase)</li>
<li filter-value="one is">one is (Lowercase)</li>
<li filter-value="two">Two</li>
<li filter-value="three">Three</li>
<li filter-value="four">Four</li>
<li filter-value="five" >Five</li>
<li filter-value="six">Six</li>
<li filter-value="seven">Seven</li>
<li filter-value="eight">Eight</li>
<li filter-value="nine">Nine</li>
<li filter-value="ten" >Ten</li>
</ul>
I have done this via using below code
var textcontent = filterItems[i].textContent;
var replacedval = "<strong>"+currval+"</strong>"
var finalval = textcontent.replace(currval, replacedval);
filterItems[i].innerHTML = finalval;
filterItems[i].style.display = 'none';
Here is working JSFiddle
https://jsfiddle.net/ku5zv3dz/
It's not possible to change the style of only a part of a text contained within an element.
To do what you ask, you have to create an additional element (say, a <span> element) which will contain only the text you want to make bold, and append it. Then, you have to remove the same text from the original element.
For example
<li filter-value="One Is">
<span class="bold">One</span> Is (Uppercase)
</li>
Since you already know which part of the text has been searched, it should be trivial to do this using String.replace() and DOM manipulation methods like document.createElement and document.appendChild.
Here's what I got. I'm a little confused with your toLowerCase and toUpperCase code, but for the most part this works. Type in 'o', or 'u', or any of the above to test. It'll bold just what you typed in (in lowercase, since that's what your code does..)
var inputId = 'filter-search';
var itemsData = 'filter-value';
var displaySet = false;
var displayArr = [];
function getDisplayType(element) {
var elementStyle = element.currentStyle || window.getComputedStyle(element, "");
return elementStyle.display;
}
document.getElementById(inputId).onkeyup = function() {
var searchVal = this.value.toLowerCase();
var filterItems = document.querySelectorAll('[' + itemsData + ']');
for (var i = 0; i < filterItems.length; i++) {
var elem = filterItems[i]; // assign it to a variable so that i don't have to constantly say filterItems[i]
if (!displaySet) {
displayArr.push(getDisplayType(elem));
}
elem.style.display = 'none';
elem.innerHTML = elem.innerHTML.replace(/<b>/g, '').replace(/<\/b>/g, ''); // strip away all previous bold
if (elem.getAttribute('filter-value').toUpperCase().indexOf(searchVal.toUpperCase()) >= 0) {
elem.style.display = displayArr[i];
if (searchVal.length > 0) {
elem.innerHTML = elem.innerHTML.replace(new RegExp(searchVal, 'g'), '<b>' + searchVal + '</b>'); // replace search with bold
}
}
}
displaySet = true;
}
.
<input type="text" id="filter-search" />
<ul>
<li filter-value="One Is">One Is (Uppercase)</li>
<li filter-value="one is">one is (Lowercase)</li>
<li filter-value="two">Two</li>
<li filter-value="three">Three</li>
<li filter-value="four">Four</li>
<li filter-value="five" >Five</li>
<li filter-value="six">Six</li>
<li filter-value="seven">Seven</li>
<li filter-value="eight">Eight</li>
<li filter-value="nine">Nine</li>
<li filter-value="ten" >Ten</li>
</ul>
JSFiddle: https://jsfiddle.net/x5amcaqr/

How to make the what happening box like twitter in our site?

I am doing this by taking the cursor position from the content-editable box. When a new tag is created the cursor comes before the tag but it should be after the tag. Also i am not able to merge/split the tag.
Please give some idea how can i do this.
Visit (https://plnkr.co/edit/DSHKEcOnBXi54KyiMpaT?p=preview) !
What i want here, after pressing the enter key for new tag the cursor should be at the end of tag while it is not and also the merging/spliting functionality like the twitter what's happening box.
Thanks in advance.
Now this code is working fr me
$scope.myIndexValue = "5";
$scope.searchTag = function(term) {
var tagList = [];
angular.forEach($rootScope.tags, function(item) {
if (item.name.toUpperCase().indexOf(term.toUpperCase()) >= 0) {
tagList.push(item);
}
});
$scope.tag = tagList;
return $q.when(tagList);
};
$scope.getTagText = function(item) {
// note item.label is sent when the typedText wasn't found
return '<a>#<i>' + (item.name || item.label) + '</i></a> ';
};
$scope.resetDemo = function() {
// finally enter content that will raise a menu after everything is set up
$timeout(function() {
//var html = "Tell us something about this or add a macro like brb, omw, (smile)";
var htmlContent = $element.find('#htmlContent');
var html = "";
if (htmlContent) {
var ngHtmlContent = angular.element(htmlContent);
ngHtmlContent.html(html);
ngHtmlContent.scope().htmlContent = html;
// select right after the #
mentioUtil.selectElement(null, htmlContent, [0], 8);
ngHtmlContent.scope().$apply();
}
}, 0);
};
HTML :
<div class="share_tags fs-12">
<div class="row margin_row">
<div class="col-md-12 no_padding">
<div class="form-group">
<div contenteditable="true" mentio
mentio-typed-term="typedTerm"
mentio-macros="macros"
mentio-require-leading-space="true"
mentio-select-not-found="true"
class="editor tag" placeholder="Tell Us something about This"
mentio-id="'htmlContent'"
id="htmlContent"
ng-model="htmlContent">
</div>
</div>
<mentio-menu
mentio-for="'htmlContent'"
mentio-trigger-char="'#'"
mentio-items="tag"
mentio-template-url="/people-mentions.tpl"
mentio-search="searchTag(term)"
mentio-select="getTagText(item)"
></mentio-menu>
</div>
</div>
<script type="text/ng-template" id="/people-mentions.tpl">
<ul class="list-group user-search">
<li mentio-menu-item="tag" ng-repeat="tag in items" class="list-group-item">
<span ng-bind-html="tag.name | mentioHighlight:typedTerm:'menu-highlighted' | unsafe"></span>
</li>
</ul>
</script>
</div>
Reference link
http://jeff-collins.github.io/ment.io/?utm_source=angular-js.in&utm_medium=website&utm_campaign=content-curation#/
is working fine for me.
This is not working perfectly but for the time being i am using this code.
In app.js
var app = angular.module('plunker', []);
app.controller('MainCtrl', function ($scope, $filter, $element) {
var tags;
$scope.allTags = ['Tag1', 'PrivateTag', 'Xtag', 'PublicTag1', 'newTag', 'socialTag', 'cricketTag'];
var replacedTag = '';
var replacedIndex;
var data;
$scope.log = function (name) {
$scope.tags = [];
$('ul').html(' ');
console.log("here", $('ul'))
var data = $('textarea').val();
replacedIndex = data.indexOf(replacedTag)
console.log('test', name, replacedTag, replacedIndex, data);
var replacedData = data.substring(0, replacedIndex - 1) + ' #' + name + data.substr(replacedIndex + replacedTag.length);
$('textarea').val(replacedData);
$('textarea').keyup();
}
f = $scope.log;
$('textarea').on('keyup', function (e) {
function getIndexOf(arr, val) {
var l = arr.length,
k = 0;
for (k = 0; k < l; k = k + 1) {
if (arr[k] === val) {
return k;
}
}
return false;
}
$('ul').html('');
$scope.tags = [];
tags = $(this).val().match(/#\S+/g);
console.log("---tags-", tags)
var a = data = $(this).val();
if (tags && tags.length) {
tags.forEach(function (tag,index) {
var index1 = getIndexOf(tags, tag);
console.log("index----",index, index1,tag)
replacedTag = tag;
$scope.tags = tag ? $filter('filter')($scope.allTags, tag.substr(1)) : [];
if ($scope.tags && $scope.tags.length && (e.keyCode && e.keCode != 32)) {
$scope.tags.forEach(function (tag1, index) {
$('ul').append('<li>' + '<a href="javascript:;" onclick=f("' + tag1 + '");>'
+ tag1 + '</a>' + '</li>')
})
}
else {
$('ul').html(' ');
}
if(index == index1) {
var b = a.substring(0, a.indexOf(tag) - 1) + ' <a>' + tag + '</a> ' + a.substr(a.indexOf(tag) + tag.length);
}
else {
var b = a.substring(0, a.lastIndexOf(tag) - 1) + ' <a>' + tag + '</a> ' + a.substr(a.lastIndexOf(tag) + tag.length);
}
a = b;
$('p').html(b)
})
}
})
});
HTML
<br>
<br>
<p></p>
<textarea rows="2" cols="80"></textarea>
<div>
<ul>
</ul>
</div>
For live demo Visit
https://plnkr.co/edit/SD9eouQa5yrViwxQD6yN?p=preview
i am also looking for the better answer.
I assume you're talking about gathering hash tags from a string of sorts, the snippet below demonstrates how you can build an array of #hashed tags without modifying the cursor position.
It uses a simple regular expression to match tags found in the textarea and then pushes them to an array.
var tags;
$('textarea').on('keyup', function(){
tags = $(this).val().match(/#\S+/g)
$('ul').html('');
tags.forEach(function(tag){
$('ul').append('<li>' + tag + '</li>')
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea></textarea>
<ul></ul>

how to make output text inside nested div with jquery

I have div inside div (nested div) and one button click and one textarea, when i click this button i want output that div in text,and add the text to Textarea
example
<div id="container">
<div class="nested">
<div id="1">
<div class="nested">
<div id="3">helpX</div>
<div id="4">helpY</div>
</div>
</div>
<div id="2">helpZ</div>
</div>
</div>
when i click my button i need the output like this =nested(=nested(helpX)(helpY))(helpZ)
my code is :
$('#BUTTONCLICK').click(function(){
$('#container').find("div").each( function(index) {
....
});
});
I hope you can help me. Thanks .
You have to set up some condition to check whether the child is a nested or child has nested children, or a simple div. So I use a recursive function to handle it:
$('#BUTTONCLICK').click(function(){
var findNest = function(ele) {
// To see if current item needs a nested prefix
var result = $(ele).hasClass("nested") ? '=nested(' : '';
$(ele).find(' > div').each(function(idx, item) {
var $item = $(item);
if ($item.hasClass("nested")) {
// If current cheked item is a nested item, nested it.
result += findNest($item);
} else if ($(item).find(".nested").length > 0) {
result += findNest(item);
} else {
// Current check item is a simple div, add it
result += '(' + $(item).text() + ')';
}
});
// Decide tail
var tail = $(ele).hasClass("nested") ? ')' : '';
return result + tail;
};
var $container = $('#container');
var result = findNest($container);
console.log(result);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<div id="container">
<div class="nested">
<div id="1">
<div class="nested">
<div id="3">helpX</div>
<div id="4">helpY</div>
</div>
</div>
<div id="2">helpZ</div>
</div>
</div>
<div id="BUTTONCLICK">click</div>
If you want to give a level limit, the code can be changed to:
$('#BUTTONCLICK').click(function(){
// Inits
var LEVEL_LIMIT = 2;
var currentLevel = 0;
var findNest = function(ele) {
// Add one level at start.
++currentLevel;
// To see if current item needs a nested prefix
var result = $(ele).hasClass("nested") ? '=nested(' : '';
$(ele).find(' > div').each(function(idx, item) {
var $item = $(item);
var $nestChilds = $(item).find(".nested");
if (currentLevel <= LEVEL_LIMIT &&
($item.hasClass("nested") || $nestChilds.length > 0)) {
// If current cheked item is a nested item, or it has child that is nest, go into it.
result += findNest($item);
} else {
// Current check item is a simple div or level limit reached,
// simply add div texts...(May need other process of text now.)
result += '(' + $(item).text() + ')';
}
});
// Decrease Level by one before return.
--currentLevel;
// Decide tail
var tail = $(ele).hasClass("nested") ? ')' : '';
return result + tail;
};
var $container = $('#container');
var result = findNest($container);
console.log(result);
});
Try
$('#BUTTONCLICK').click(function(){
var text = '';
$('#container').find("div").each( function(index) {
text += $(this).text();
});
$("textarea").val(text);
});
$('#BUTTONCLICK').click(function(){
var findNest = function(ele) {
// To see if current item needs a nested prefix
var result = $(ele).hasClass("nested") ? '=nested(' : '';
$(ele).find(' > div').each(function(idx, item) {
var $item = $(item);
if ($item.hasClass("nested")) {
// If current cheked item is a nested item, nested it.
result += findNest($item);
} else if ($(item).find(".nested").length > 0) {
// For all .nested child from the item, do the findNest action
$(item).find(".nested").each(function(idx, item) {
result += findNest(item);
});
} else {
// Current check item is a simple div, add it
result += '(' + $(item).text() + ')';
}
});
// Decide tail
var tail = $(ele).hasClass("nested") ? ')' : '';
return result + tail;
};
var $container = $('#container');
var result = findNest($container);
console.log(result);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<div id="container">
<div class="nested">
<div id="1">
<div class="nested">
<div id="3">helpX</div>
<div id="4">helpY</div>
</div>
</div>
<div id="2">helpZ</div>
</div>
</div>
<div id="BUTTONCLICK">click</div>

change text color of matching text from input in javascript

Here is my code
And I am trying to change the color of any match in the <li> elements that matches the text in the <input> element. So if you type lets say "this is a simple text" the result should look like this:
<input value="this is a simple text" id="term"/>
<ul id="ul-id" >
<li id="li-id-1"> hello budy <span style="color:red">this</span> <span style="color:red">is</span> really <span style="color:red">simple</span> stuff </li>
<li id="li-id-2"> <span style="color:red">this</span> <span style="color:red">is</span> it</li>
<li id="li-id-3"> there <span style="color:red">is</span> something here</li>
<li id="li-id-4"> plain <span style="color:red">text</span> file</li>
</ul>
Any help would be appreciated.
Thank you.
You can remove the delay function if you like, but this would lead to a performance loss:
// https://stackoverflow.com/a/9310752/1636522
RegExp.escape = function (text) {
return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
};
window.addEventListener('load', function () {
var wrapper = '<span style="background:yellow">$&</span>';
var input = document.getElementById('term');
var list = document.getElementById('ul-id');
var items = list.getElementsByTagName('li');
var l = items.length;
var source = Array.prototype.map.call(
items, function (li) { return li.textContent; }
);
var cmp = function (a, b) {
return b.length - a.length;
};
var delay = function (fn, ms) {
var id, scope, args;
return function () {
scope = this;
args = arguments;
id && clearTimeout(id);
id = setTimeout(function () {
fn.apply(scope, args);
}, ms);
};
};
term.addEventListener('keyup', delay(function () {
var i, re, val;
if (val = this.value.match(/[^ ]+/g)) {
val = val.sort(cmp).map(RegExp.escape);
re = new RegExp(val.join('|'), 'g');
for (i = 0; i < l; i++) {
items[i].innerHTML = source[i].replace(re, wrapper);
}
}
else {
for (i = 0; i < l; i++) {
items[i].textContent = source[i];
}
}
}, 500));
});
<input value="" id="term"/>
<ul id="ul-id" >
<li id="li-id-1"> hello budy this is really simple stuff </li>
<li id="li-id-2"> this is it</li>
<li id="li-id-3"> there is something here</li>
<li id="li-id-4"> plain text file</li>
</ul>
Similar topic: https://stackoverflow.com/a/20427785/1636522.
I don't know if it is possible with only RegEx, but here is a jQuery solution:
$('#term').change(function() {
var inpArr = $(this).val().split(" ");
$('#ul-id li').each(function() {
var liArr = $(this).text().split(" ");
var txt = "";
$.each(liArr, function(i, v) {
if(inpArr.indexOf(v) > -1) {
txt += "<span class='red'>"+ v +"</span> ";
} else {
txt += v + " ";
}
});
$(this).html(txt);
});
});
span.red {
color: red;
}
And the working fiddle: https://jsfiddle.net/ermk32yc/1/
Plain JS solution
var list = document.querySelector('#ul-id'),
listItem,
listItems,
term = document.querySelector('#term'),
oldRef = list.innerHTML,
oldValue;
term.addEventListener('keyup', function () {
var regExp,
value = term.value;
if (oldValue !== value) {
oldValue = value;
// Reset
list.innerHTML = oldRef;
if (value.trim() !== '') {
listItems = list.querySelectorAll('#ul-id li');
regExp = new RegExp(term.value, 'g');
// Perform matching
for (var i = 0; i < listItems.length; i++) {
listItem = listItems[i];
listItem.innerHTML = listItem.innerHTML.replace(regExp, function (match) {
return '<span class="matched">' + match + '</span>';
});
}
}
}
}, false);
.matched {
color: red;
}
<input id="term"/>
<ul id="ul-id" >
<li id="li-id-1"> hello budy this is really simple stuff </li>
<li id="li-id-2"> this is it</li>
<li id="li-id-3"> there is something here</li>
<li id="li-id-4"> plain text file</li>
</ul>
You might do something like this
$('#term').change(function (i) {
var terms = $('#term').val().split(" ");
$('#ul-id > li').each(function (i, el) {
var val = $(el).html().replace(/<[^<]+>/g, ''),
match;
terms.forEach(function (term) {
val = val.replace(new RegExp(term, 'g'),
'<span style="color:red">' + term + '</span>');
});
$(el).html(val);
});
});
https://jsfiddle.net/1vm0259x/5/
You can use the below solution if there is no html contents in the li elemnets
if (!RegExp.escape) {
RegExp.escape = function(value) {
return value.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&")
};
}
var lis = [].slice.call(document.querySelectorAll('#ul-id li'));
lis.forEach(function(el) {
el.dataset.text = el.innerHTML;
});
document.querySelector('#term').addEventListener('change', function() {
var parts = this.value.split(' ').map(function(value) {
return '\\b' + RegExp.escape(value) + '\\b';
});
var regex = new RegExp(parts.join('|'), 'g');
lis.forEach(function(el) {
el.innerHTML = el.dataset.text.replace(regex, function(part) {
return '<span class="highlight">' + part + '</span>'
})
});
});
.highlight {
color: red;
}
<input id="term" />
<ul id="ul-id">
<li id="li-id-1">hello budy this is really simple stuff</li>
<li id="li-id-2">this is it</li>
<li id="li-id-3">there is something here</li>
<li id="li-id-4">plain text file</li>
</ul>
With jQuery
if (!RegExp.escape) {
RegExp.escape = function(value) {
return value.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&")
};
}
$('#term').on('change keyup', function() {
//$('#ul-id li .highlight').contents().unwrap();//remove previous highlights
var parts = this.value.split(' ').map(function(value) {
return '\\b' + RegExp.escape(value) + '\\b';
});
var regex = new RegExp(parts.join('|'), 'g');
$('#ul-id li ').each(function() {
var text = $(this).text();
$(this).html(text.replace(regex, function(part) {
return '<span class="highlight">' + part + '</span>'
}))
})
});
.highlight {
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input id="term" />
<ul id="ul-id">
<li id="li-id-1">hello budy this is really simple stuff</li>
<li id="li-id-2">this is it</li>
<li id="li-id-3">there is something here</li>
<li id="li-id-4">plain text file</li>
</ul>
you can handle blur event or you can copy paste the inner function code to wherever it is required. this is the guide code here you can more explore match function as per your requirement and then can traverse your li elements as shown below.
$('#term).blur(function() {
$('#ul-id li').foreach(function()
{
if($(this).text().match($("#term").text()))
{
///set/change here color of li element
$(this).css('color', 'red');
}
}
}

prevent adding duplicate items to the basket

I have created a basket in my PHP form where users can insert their selected movies to it.
Question:
How can I prevent adding duplicate movies to this basket (selected movie list)?
Here is my code: (Sorry, I didn't paste all the code since it was too long)
<div id="basket">
<div id="basket_left">
<h4>Selected Movies</h4>
<img id="basket_img" src="http://brettrutecky.com/wp-content/uploads/2014/08/11.png" />
</div>
<div id="basket_right">
<div id="basket_content">
<span style="font-style:italic">Your list is empty</span>
</div>
</div>
</div>
<script type="text/javascript">
var master_basket = new Array();
$(document).ready(function () {$("input[id='selectType']").change(function(){
// AUTO_COMPLETION PART
$('#btnMove').on('click', function(d) {
console.log(master_basket);
d.preventDefault();
var selected = $("#q").val();
if (selected.length == 0) {
alert("Nothing to move.");
d.preventDefault();
} else {
var obj = {
"movie_name":selected,
"movie_info": ""
};
addToBasket(obj);
}
$("#q").val("");
});
});
function addToBasket(item) {
master_basket.push(item);
showBasketObjects();
}
function showBasketObjects() {
$("#basket_content").empty();
$.each(master_basket, function(k, v) {
$("#basket_content").append("<div class='item_list'>" + v.movie_name + "<a class='remove_link' href='" + k + "'><img width='20' src='http://i61.tinypic.com/4n9tt.png'></a></div>");
});
I personally wouldn't suggest using javascript to prevent this duplication thing since anyone could modify it and manually cause this problem, you should prevent the duplication both in php and javascript.
Anyway to accomplish what you want in the script I think it's enough to modify part of your code to this:
var master_basket = new Array();
selectedMovies = {};
///////
} else {
var obj = {
"movie_name":selected,
"movie_info": ""
};
if(!selectedMovies.hasOwnProperty(selected)){
addToBasket(obj);
selectedMovies[selected] = obj;
}
}
Try modifying your function to
function addToBasket(item) {
var ifExists = false;
for (i = 0; i < master_basket.length; ++i) {
if(master_basket[i] == item)
ifExists = true;
}
if(!ifExists)
master_basket.push(item);
}
}

Categories