Jquery: Parsing HTML - javascript

I need help in parsing href tags. Currently, everything is being parsed as text, however I need to parse the links so that I can send it to the php page later using AJAX.
my HTML looks like:
<div id="word_content">
<br>Testing Time: 2015-10-29 17:57:11<br>
Total Age: 19<br>
Total Friemd: 9<br>
Total Family: 10<br>
<br>
Here are the suggestions - Him_530037_: 93358546
<h3>Overview</h3><br>
<ul>
<li>(The overlap provided is not good)</li>
</ul>
<h3>Structure</h3><br>
<h4>Target:</h4><br>
<ul>
<li>Audience.</li>
<li>Lookalike</li>
<li>Overlap of Audience</li>
06<font name="names" hidden="" style="display: inline;"> - Page Likes</font>
</ul>
Jquery Code is something like this:
var headTags = $("div#word_content").find("*").filter(function(){
return /^h/i.test(this.nodeName);
});
var output = {};
$(headTags).each(function(){
var currentHead = $(this);
var nextNextElem = currentHead.next().next();
var innerText = [];
if(nextNextElem.prop("tagName") == "UL")
{
nextNextElem.find("li").each(function(){
innerText.push($(this).text());
});
}
output[currentHead.text()] = innerText;
});
Currently, the Jquery is fetching the data, but it is capturing only the text and not the link. I need to parse the link as well, so that this link could be used in further pages. Can someone please help.

use this:
nextNextElem.find("a").each(function(){
innerText.push($(this).text()+" & href is:"+$(this).attr("href"));
});
var headTags = $("div#word_content").find("*").filter(function(){
return /^h/i.test(this.nodeName);
});
var output = {};
$(headTags).each(function(){
var currentHead = $(this);
var nextNextElem = currentHead.next().next();
var innerText1 = [];
if(nextNextElem.prop("tagName") == "UL")
{
nextNextElem.find("li").each(function(index){
innerText1.push(this.firstChild.data);
$(this).children().each(function(index){
innerText1.push("<a href='"+$(this).attr("href")+"'>"+$(this)[0].innerText+"</a>");
if($(this).prop('nextSibling')){
innerText1.push($(this).prop('nextSibling').nodeValue);
}
});
});
}
output[currentHead.text()] = innerText1;
}); console.log(output);
$("#data").html(JSON.stringify(output));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="word_content">
<br>Testing Time: 2015-10-29 17:57:11<br>
Total Age: 19<br>
Total Friemd: 9<br>
Total Family: 10<br>
<br>
Here are the suggestions - Him_530037_: 93358546
<h3>Overview</h3><br>
<ul>
<li>Multiple Countries
603<font name="names" hidden="" style="display: none;"> - Post: "သင့္ရဲ့ Data အသံုးျပဳ မွုကို အေၾကာင္းၾကားေပးေသာ..."</font> (MM, SG),
602<font name="names" hidden="" style="display: none;"> - Post: "Mynamar pics."</font></li>
</ul>
</div>
<span>OUTPUT AREA:</span>
<div id="data"></div>

You can use something like this to parse links in the site:
$("a").each(function(i, o) {
console.log("Link: " + (i + 1));
console.log(" Text is: " + $(o).text());
console.log(" Link is: " + $(o).attr('href'));
})
Result:
www.mytarget.com=
https://www.myPage.com/lolPagess/?id=06
See JsFiddle

Check every href inside an a
$("a").each(function () {
isUrlValid($(this).attr("href"));
});
borrowed from Validating url with jQuery without the validate-plugin?:
function isUrlValid(url) {
return /^(https?|s?ftp):\/\/(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*#)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|#)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|#)*)*)?)?(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|#)|[\uE000-\uF8FF]|\/|\?)*)?(#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|#)|\/|\?)*)?$/i.test(url);
}
This regex will test for valid url's.

Related

Issues with using AJAX and JQuery to multiselect and capture information from JSON file

I have a live search function that parses information from a JSON file using AJAX and jQuery, and then is clickable. What I'm struggling to figure out is how to have the value (in this case, "happy" or "fat") populate a multiselect, and then once that's accomplished, capture the rest of the data in that JSON array to be utilized later.
$(document).ready(function(){
$.ajaxSetup({ cache: false });
$('#search').keyup(function(){
$('#result').html('');
$('#state').val('');
var searchField = $('#search').val();
var expression = new RegExp(searchField, "i");
$.getJSON('coretype.json', function(data) {
$.each(data, function(key, value){
if (value.identifier.search(expression) != -1)
{
$('#result').append('<li class="list-group-item link-class"> '+value.identifier+'</li>');
}
});
});
});
$('#result').on('click', 'li', function() {
var click_text = $(this).text().split('|');
$('#search').val($.trim(click_text[0]));
$("#result").html('');
});
});
I have gotten all the way to having the value be clickable, and have been unsuccessful figuring out the rest from there.
Here's the JSON file:
[
{
"identifier":"Happy",
"progressbar1": 3,
"progressbar2": 2,
"progressbar3": -2
},
{
"identifier":"Fat",
"progressbar1": -3,
"progressbar2": -2,
"progressbar3": 2
}
]
Ideally I'd like javascript to be able to capture the "progressbarX" values when someone types in the identifier, although I figure there's a much easier way to accomplish this...
<!-- Search -->
<br /><br />
<div class="container" style="width:900px;">
<h2 align="center">EnneaTest</h2>
<br /><br />
<div align="center">
<input type="text" name="search" id="search" placeholder="trait type" class="form-control" />
</div>
<ul class="list-group" id="result"></ul>
<br />
</div>
</div>
</div>
Here's the Plunker file
I created a kind of autocomplete drop down for search from json. And once one of the options from that dropdown is selected, I add that to the result list. At that time the whole object is pushed into searchObjects object. When the item from the list is clicked, that text is used to search the object associated with it. Hope this helps..
<!-- Search -->
<br /><br />
<div class="container" style="width:900px;">
<h2 align="center">EnneaTest</h2>
<br /><br />
<div align="center">
<input type="text" name="search" id="search" placeholder="trait type" class="form-control" />
</div>
<div id="searchResult"></div>
<div>
<ul class="list" id="result" style="color: red;"></ul>
</div>
<br />
</div>
<script>
$(document).ready(function(){
$.ajaxSetup({ cache: false });
$('#search').keyup(function(){
var searchField = $('#search').val();
var regex = new RegExp(searchField, "i");
var output = '<div class="row">';
$.getJSON('coretype.json', function(data) {
$.each(data, function(key, val){
if (val.identifier.search(regex) !== -1) {
console.log(val);
var thisVal = JSON.stringify(val);
output += "<h5 onclick='addToList("+thisVal+")'>" + val.identifier + "</h5>";
}
});
output += '</div>';
$('#searchResult').html(output);
});
});
$('#result').on('click', 'li', function() {
var click_text = $(this).text();
console.log(click_text);
var thisObj = [];
thisObj = findObject(click_text);
console.log(thisObj);
});
});
var searchObjs = [];
function addToList(obj) {
//console.log(obj);
$('#result').append('<li class="list-group-item link-class">'+obj.identifier+'</li>');
$('#searchResult').html('');
var item = {};
item ["identifier"] = obj.identifier;
item ["progressbar1"] = obj.progressbar1;
item ["progressbar2"] = obj.progressbar2;
item ["progressbar3"] = obj.progressbar3;
searchObjs.push(item);
console.log(searchObjs);
}
function findObject(identifier) {
var found = 0;
for (var i = 0, len = searchObjs.length; i < len; i++) {
if (searchObjs[i].identifier === identifier) {
return searchObjs[i]; // Return as soon as the object is found
found = 1;
}
}
if(found === 0) {
return null; // The object was not found
}
} ;
</script>

how to match the single string and return whole string using js

I have code :
To search a single string and return whole string.
$(document).ready(function() {
$('button').click(function (){
var search = $('#input').val();
var str = $('#file').html();
var output=str.match(search );
document.getElementById("result").innerHTML = output;
if (search.value.length > 0) {
$(".oh").show().filter(function () {
return $('#input').find('li').text().toLowerCase().indexOf($("search").val().toLowerCase()) == -1;
}).hide();
}
else {
$(".oh").show();
document.getElementById( 'oh' ).style.display = 'block';
}
});
});
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script src="searchbox.js"></script>
</head>
<body>
<input type="text" id="input">
<button>solve</button>
<p id="result"></p>
<div id="file"class="oh"style="display:none;">
<li>beatiful</li>
<li>happy sunday</li><li>good morning</li><li>good evening</li><li>oh my god</li>I like u</li><li>wonderful day</li>
<li>good aftnoon</li>
</div>
</body>
</html>
For example:
`input = good
output = good morning,
good night,
good noon`
`input = morning,
output = good morning`
Its like a search box inside html
Please help me with any suggestion or correct my code its more helpful for me i have use jquery and index() are using but its not work
Check this, i have updated your markup little bit and changed the code to work:
$(document).ready(function() {
$('button').click(function() {
var search = $('#input').val(); // get the search term
var $lis = $('#file li'); // all the existing li items to filter/search
var $resUl = $('#result ul'); // the ul to show results
var o = $lis.map(function() { // map will let you loop through list items
if (this.textContent.indexOf(search) != -1) { // check if the current li in the iteration has the search term
return $(this).clone(); // if yes then return a copy of it.
}
}).get(); // .get() will create an array when used with .map()
$resUl.empty(); // always clear the result ul
$.each(o, function(i, item) { // loop through the array created via filter
$resUl.append(item).find('li').fadeIn(); // here append them as lis are hidden so fade them in the view to show.
});
});
});
#file li {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<input type="text" id="input">
<button>solve</button>
<div id="result">
<ul></ul>
</div>
<ul id="file">
<li>beatiful</li>
<li>happy sunday</li>
<li>good morning</li>
<li>good evening</li>
<li>oh my god</li>
<li>I like u</li>
<li>wonderful day</li>
<li>good aftnoon</li>
</ul>
$(document).ready(function() {
$('button').click(function (){
var searchval = $('#input').val();
var str = $('#file').html();
var rep2 = str.split('</li>');
var rep3 = rep2.filter(function(item){
if(item.search(searchval) !=-1){
return item;
}
})
document.getElementById("result").innerHTML = rep3;
});
});

auto-complete jquery doesn't work with with ngmodel and ngrepeat (angular)

I am trying to use autocomplete function of jquery inside my angular controller and that doesn't work may be because of ng-model or ng-repeat I don't know exactly ^^
My html file contains this code
<div ng-if="data._id" data-ng-controller="AddonExclusivityCtrl" ng-init="init()">
<hr>
<label>Add an addon that is not bookable with this one:</label>
<input id="addon-search" type="text"
ng-model="addon_filter_name"
class="form-control" placeholder="Search for an addon...">
<br>
<div ng-show="data._embedded.exclusive_with && data._embedded.exclusive_with.length > 0">
<label>Not bookable with:</label>
<ul>
<li ng-repeat="exclusive_with in data._embedded.exclusive_with">
{{exclusive_with.description}} <a href="#"
ng-click="removeExclusivity($event, exclusive_with)"
title="Remove mutual exclusivity">
<span class="glyphicon glyphicon-trash"></span></a>
</li>
</ul>
</div>
</div>
And my controller contains the following code :
var lastFetchedAddonList = [];
$scope.init = function() {
$('#addon-search').autocomplete({
source: function( request, response ) {
Addon.query({ name: request.term, global: null }, function(results) {
lastFetchedAddonList = results.data;
var suggestions = [];
angular.forEach(results.data, function(v, i){
suggestions.push({ label: v.description, value: i });
});
response(suggestions);
});
},
select: function( event, ui ) {
event.preventDefault();
if ($scope.data._embedded === undefined) {
$scope.data._embedded = [];
}
if ($scope.data._embedded.exclusive_with === undefined) {
$scope.data._embedded.exclusive_with = [];
}
var addon = lastFetchedAddonList[ui.item.value];
var exclusiveAddon = new AddonExclusivity();
exclusiveAddon._id = $scope.data._id;
exclusiveAddon.exclusive_with_addon = addon.name;
AddonExclusivity.save(exclusiveAddon, function(){
$rootScope.addNotification('Added ' + addon.description + ' as mutually exclusive with ' + $scope.data.description);
$scope.data._embedded.exclusive_with.push(addon);
$('#addon-search').val('');
});
return false;
}
});
};
$scope.removeExclusivity = function($event, addon) {
$event.preventDefault();
AddonExclusivity.delete({ id: $scope.data._id, other_id: addon.name }, function(){
$rootScope.addNotification('Addon ' + addon.description + ' is not anymore mutually exclusive with ' + $scope.data.description);
$scope.data._embedded.exclusive_with.splice($scope.data._embedded.exclusive_with.indexOf(addon), 1);
});
};
Thank you for your help in advance :)
Instead of using jquery autocomplete, you can use plain html to create your autocomplete.
See this post here
I have the same problem. The reason is angularjs repeat ng-model tag the id is always the same.
So only the first tag with that id works fine with autocomplete.
but the second and after with same id would not work.
I am looking at angular-module angucomplete-alt angucomplete-alt
This should solve your problem.

jQuery selectable serialize into an array

I have a selectable:
<ol id="selectable">
<li class="ui-widget-content">1</li>
<li class="ui-widget-content">2</li>
<li class="ui-widget-content">3</li>
</ol>
I want to capture every selected item body into a hidden input separated by a comma, so after selecting some items it would look for example like this:
<input type="hidden" id="bad_times" name="bad_times" value="1,3" />
where 1,3 are bodies of the items selected. Any examples from the web I tried failed to work. Please note that only selected items have to be captured, if I select some item, then unselect, then select again it should appear only once. How to achieve it?
Following assumes that jQuery UI selectable plugin is being used
If so you can try something like this and build on it
$(function() {
$("#selectable").selectable({
filter: "li" ,
unselected:mapSelected,
selected:mapSelected
});
});
function mapSelected(event,ui){
var $selected = $(this).children('.ui-selected');
var text = $.map($selected, function(el){
return $(el).text()
}).join();
$('#bad_times').val(text)
}
DEMO
What have you tried so far and where were you running into issues?
Based on the docs the selected items have the class 'ui-selected'
So you should just be able to iterate over the selected items something like:
var str = "";
$( ".ui-selected").each(function(i) {
if (i > 0)
str += ",";
str += $(this).text();
});
$('#bad_times').val(str);
I would be in favor of using a data attribute, say, data-value and using an array, [1,3], instead of a list 1,3.
Special Note: The demo and code below simply help to verify the concept and do not use the selectable plugin.
HTML:
<input type="hidden" id="bad_times" name="bad_times" data-value="[]" />
JS:
$(function() {
var hidden = $('#bad_times');
$('#selectable li').on('click', function() {
var val = +$(this).text();
hidden.data()['value'].indexOf(val) > -1 || hidden.data()['value'].push(val);
console.log( hidden.data()['value'] );
});
});
$(function() {
var hidden = $('#bad_times');
$('#selectable li').on('click', function() {
var val = +$(this).text();
hidden.data()['value'].indexOf(val) > -1 || hidden.data()['value'].push(val);
$('pre.out').text( JSON.stringify( hidden.data()['value'] ) );
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ol id="selectable">
<li class="ui-widget-content">1</li>
<li class="ui-widget-content">2</li>
<li class="ui-widget-content">3</li>
</ol>
<input type="hidden" id="bad_times" name="bad_times" data-value="[]" />
<pre class="out"></pre>

jquery removing string parts from two areas

I'm looking to expand on a recent script i've coded using jquery.
I have this following code
<script type='text/javascript'>
added_departments = new Array();
$("#departments_submit").click(function(){
var depo = $("#depo_list").val();
if(jQuery.inArray(depo, added_departments) != -1)
{
return false;
}
else
{
added_departments.push(depo);
$("#depo_added_list").append("<li>" + depo + "<a href='#' title='"+ depo +"' class='remove_depo'> [X] </a></li>");
var current_value = $("#departments").val();
if(current_value)
{
$("#departments").val(current_value + "," + depo);
}
else
{
$("#departments").val(depo);
}
return false;
}
});
</script>
The above code takes information selected in a select drop down box, adds it to a div to display publicly and also into a hidden form field that processes the data.
i've tried to create now something that will reverse this effect and remove certain selections from the div and the field. which is where i have this code
<script type='text/javascript'>
$(".remove_depo").click(function(){
var removing = $(this).title();
var current_val = $("#deparments").val();
if(current_val == removing) {
$("departments").replace(removing, "");
}
else {
$("departments").replace("," + removing, "");
}
});
</script>
It doesn't cause any errors, but it doesn't do anything either? So I'm really stuck. Any ideas?
EDIT: Updated code
$(".remove_depo").click(function(){
var removing = $(this).attr('title');
var current_val = $("#deparments").val();
if(current_val == removing) {
$("#departments").replace(removing, "");
}
else {
$("#departments").replace("," + removing, "");
}
});
Here is the html
<form method="post" action="javascript:void(0);">Select Departments To Be Added:
<div class="depo_adder">
<select id="depo_list"><option value="">--- INDIVIDUAL TAGS ---</option><option value="blah">blah</option></select>
<button id="departments_submit">Go!</button>
</div></form><form method="post" action="briefings/addbriefing.php">
<div class="form">
<strong>Departments: </strong>
<ul id="depo_added_list"><li>blah [X] </li></ul>
<input name="departments" id="departments" value="blah" type="hidden">
</div>
you're referring to $('departments') - this won't work. You need to specify either an identifierm eg $('#departments') or a class, eg $('.departments)
ah - other answer is also correct, .title() is not a function. You want
$('#foo').attr('title') to get the title.

Categories

Resources