jQuery selectable serialize into an array - javascript

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>

Related

Get child element attribute using Jquery

I have a html structure. I want to get all controltypeid value in a function. I just try like
$('#firstDiv > a.[controltypeid]').each(function (i, val) {
$Control = $(val);
});
<div id="firstDiv">
<a id="1" controltypeid="1"></a>
<a id="2" controltypeid="2"></a>
<a id="3" controltypeid="3"></a>
</div>
but I can't get the value.Can any one help. Thanks in advance for help.
Done using jquery children selector.
Description :Get the children of each element in the set of matched elements.
Code :
$(document).ready(function(){
$("#firstDiv").children('a[controltypeid]').each(function(){
alert($(this).attr('controltypeid'))
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="firstDiv">
<a id="1" controltypeid="1"></a>
<a id="2" controltypeid="2"></a>
<a id="3" controltypeid="3"></a>
</div>
You could also use simply like this
$('#firstDiv a').each(function () {
alert($(this).attr('controltypeid'));
});
Try this if you need your controltypeid in a array:
var controltypeid = [];
$('#firstDiv > a[controltypeid]').each(function (i, v) {
controltypeid.push($(v).attr( "controltypeid" ));
});
console.log(controltypeid);
Did everyone forget about .map?
Example:
var controlTypeIds = $('#firstDiv').children().map(function() {
return $(this).attr('controltypeid');
}); // ['1', '2', '3']
Or, if you want to continue using your selector, remove the extra .. The . selector selects class, but having a attribute selector right after it .[...] makes no sense and is not syntactically correct.
var controlTypeIds = $('#firstDiv>a[controltypeid]').map(function() {
return $(this).attr('controltypeid');
}); // ['1', '2', '3']
a.[controltypeid] is wrong and is replaced by a[controltypeid]
secondly, use attr() to get the attribute value.
$('#firstDiv > a[controltypeid]').each(function () {
console.log( $( this ).attr( "controltypeid" ) );
});
if you just want to get all the values in a string
var controltypeids = [];
$('#firstDiv > a[controltypeid]').each(function () {
controltypeids.push( $( this ).attr( "controltypeid" ) );
console.log( $( this ).attr( "controltypeid" ) );
});
alert( controltypeids.join( "," ) );
You can get following way using JQuery. using attr
Make following changes in Jquery.
$('#firstDiv > a').each(function () {
alert($(this).attr('controltypeid'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="firstDiv">
<a id="1" controltypeid="1"></a>
<a id="2" controltypeid="2"></a>
<a id="3" controltypeid="3"></a>
</div>

Jquery: Parsing HTML

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.

jQuery script for finding elements by typing and organize them

I would like to search by any term (name, user, from, price), and display the div into top and hide the ones who doesn't have the typed value.
Here's the jsfiddle: http://jsfiddle.net/Sc9ys/10/
I would like to have the same result as the jquery mobile table filter http://demos.jquerymobile.com/1.4.0/filterable/
Where you can search for any term.
I know that for search for any term I should use $(list).find("li *:)... but I can't figure out how to display the items properly. If you test my jsfiddle it doesn't work very well.
Edit: As asked by the user below, here's some more info.
<ul id='list'>
<li>
<div class='row'>
<div class='middle'>
<ul>
<li><h3>Stackoverflow</h3></li>
<li><span>User</span></li>
<li><span>London</span></li>
</ul>
</div>
<div style='clear: both'></div>
</div>
</li>
</ul>
$("#search").change( function () {
$(list).find("li *:not(:Contains(" + filter + "))").parent().hide();
});
DEMO
The idea is in
$("#ul_container").find("li").filter(function () {//your comparing logic here });
Here, try this out. Honesty I couldn't read thru your code, so I made this example. I added the sub items (spans that contain data to be searched) in an array datalist by their class name.
Generic Search Function.
HTML
<input type="text" id="search" />
<ul id="ul_container">
<li class="listItem">
<span class="car">Honda</span>
<span class="country">Japan</span>
</li>
<li class="listItem">
<span class="car">BMW</span>
<span class="country">Germany</span>
</li>
</ul>
Script:
//Capture user input
$("#search").on("keyup change", function () {
var str = $.trim($(this).val());
if (str) {
search(str);
} else {
// if no input, then show all
$(".listItem").show();
}
});
//the search part.
var datalist = ["car", "country"];
function search(toFind) {
//select all li and loop thru them one by one
$("#ul_container").find("li").filter(function () {
var $li = $(this);//hold current li in a variable
//loop thru all sub spans by their class and check if the toFind keyword is there
// you modify this step, i use it to specify which sub span to be searched. Sometimes I don't want all field to be searched, only the ones I select.
for (var i = 0; i < datalist.length; i++) {
//hold the span in a var called $item
var $item = $li.children("." + datalist[i]);
var content_str = $item.html();//get the actual string
//the comparing code
if (content_str.toLowerCase().indexOf(toFind.toLowerCase()) >= 0) {
$li.show();
break;
} else {
$li.hide();
}
}
});
}
Solved guys. Thank you all.
You can see the following example working at: http://jsfiddle.net/Sc9ys/29/
$('#search').on('keyup change', function(){
var str = $.trim($(this).val());
if (str) {
search(str, $("#list"));
} else {
$("#list").find('li').show();
/* The <li> are display: none, to show them again if the input type is clear,
we must find those <li> and show them. Showing only the #list isn't enough. */
}
});
function search(toFind, list){
$(list).find('li').filter(function() {
$li = $(this);
$li.find(".middle :contains(" + toFind +")").parent().parent().slideDown();
$li.find(".middle").not(":contains(" + toFind + ")").parent().parent().slideUp();
});
}
/* Function to search with the input lowercase */
$.expr[":"].contains = $.expr.createPseudo(function(arg) {
return function( elem ) {
return $(elem).text().toUpperCase().indexOf(arg.toUpperCase()) >= 0;
};
});
Edit: Made some adjustments according to the help of user #Joraid.

How to add array items to <li> Jquery

I'm working on something really simple, a short quiz, and I am trying to make the items I have listed in a 2-d array each display as a <li>. I tried using the JS array.join() method but it didn't really do what I wanted. I'd like to place them into a list, and then add a radio button for each one.
I have taken the tiny little leap to Jquery, so alot of this is my unfamiliarity with the "syntax". I skimmed over something on their API, $.each...? I'm sure this works like the for statement, I just can't get it to work without crashing everything I've got.
Here's the HTML pretty interesting stuff.
<div id="main_">
<div class="facts_div">
<ul>
</ul>
</div>
<form>
<input id="x" type="button" class="myBtn" value="Press Me">
</form>
</div>
And, here is some extremely complex code. Hold on to your hats...
$(document).ready (function () {
var array = [["Fee","Fi","Fo"],
["La","Dee","Da"]];
var q = ["<li>Fee-ing?","La-ing?</li>"];
var counter = 0;
$('.myBtn').on('click', function () {
$('#main_ .facts_div').text(q[counter]);
$('.facts_div ul').append('<input type= "radio">'
+ array[counter]);
counter++;
if (counter > q.length) {
$('#main_ .facts_div').text('You are done with the quiz.');
$('.myBtn').hide();
}
});
});
Try
<div id="main_">
<div class="facts_div"> <span class="question"></span>
<ul></ul>
</div>
<form>
<input id="x" type="button" class="myBtn" value="Press Me" />
</form>
</div>
and
jQuery(function ($) {
//
var array = [
["Fee", "Fi", "Fo"],
["La", "Dee", "Da"]
];
var q = ["Fee-ing?", "La-ing?"];
var counter = 0;
//cache all the possible values since they are requested multiple times
var $facts = $('#main_ .facts_div'),
$question = $facts.find('.question'),
$ul = $facts.find('ul'),
$btn = $('.myBtn');
$btn.on('click', function () {
//display the question details only of it is available
if (counter < q.length) {
$question.text(q[counter]);
//create a single string containing all the anwers for the given question - look at the documentation for jQuery.map for details
var ansstring = $.map(array[counter], function (value) {
return '<li><input type="radio" name="ans"/>' + value + '</li>'
}).join('');
$ul.html(ansstring);
counter++;
} else {
$facts.text('You are done with the quiz.');
$(this).hide();
}
});
//
});
Demo: Fiddle
You can use $.each to iterate over array[counter] and create li elements for your options:
var list = $('.facts_div ul');
$.each(array[counter], function() {
$('<li></li>').html('<input type="radio" /> ' + this).appendTo(list);
}
The first parameter is your array and the second one is an anonymous function to do your action, in which this will hold the current element value.
Also, if you do this:
$('#main_ .facts_div').text(q[counter]);
You will be replacing the contents of your element with q[counter], losing your ul tag inside it. In this case, you could use the prepend method instead of text to add this text to the start of your tag, or create a new element just for holding this piece of text.

Sortable list to update hidden input

I have an unordered list that is sortable using jQuery. The sort function(s) works fine and is below. Each list item has an id on this format- id="post_#" where the # is a unique number. I need to update the hidden input value with the order of the list items after they're sorted, but only the #. So if the order of the items was > post_3, post_2, post_4, post_1 < then the input value would be- value="3,2,4,1"
Here's the jQuery I have so far-
<script type="text/javascript">
jQuery(document).ready(function(){
jQuery(function() {
jQuery("#wpbody-content #post_sortable_list").sortable({ opacity: 0.6, cursor: \'move\', update: function() {
var order = $(this).sortable;
}
});
});
});
</script>
And the HTML-
<div id="wpbody-content">
<ul id="post_sortable_list">
<li id="post_1">foo</li>
<li id="post_2">bar</li>
<li id="post_3">hello</li>
<li id="post_4">world</li>
</ul></div>
<input type="hidden" name="posts_order" value="" />
can you do something like
var order = '';
$('#post_sortable_list').find('li').each( function () {
order = order + $(this).text().substring(5);
});
$('posts_order').val(order);
possible i'm way off base
<script type="text/javascript">
jQuery(document).ready(function(){
jQuery(function() {
jQuery("#wpbody-content #post_sortable_list").sortable({ opacity: 0.6, cursor: \'move\', update: function() {
var order = $(this).map(function(i, e){
return $(e).attr("id").substring(5);
}.join(", ");
}
});
});
});
</script>
Try using map to get all the Ids and then joining them into a string.

Categories

Resources