Sortable list to update hidden input - javascript

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.

Related

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;
});
});

JavaScript keeping array in order

I am trying to keep an array in a particular order, and I've learned about the splice function to insert in a specific index location, but it doesn't seem to do the right thing.
Here's a fiddle of what I have so far: http://jsfiddle.net/drumichael/7r2pV/277/
In section 1, you can select one or many of the options, however "First" should always be 1st, "second" 2nd, and "Fourth" after both of those. If you only choose "First" & "Fourth", they should be in that order regardless of the order in which you checked the boxes.
In section 2 - you may only choose ONE of Options A, B, & C... and that option should always be in the 3rd position of the array (unless you didn't choose ANY items from Section 1 of course, it would be all by itself inside the array).
Honestly I'm not sure where to go from here. I've tried this:
var array_position = $(this).attr('id');
var messagePart = $(this).attr('data-message');
message.splice(array_position, 0, messagePart);
But they still dont end up in the proper order.
Since the id's are numbered in the order you want, you can sort $('.mycheckbox:checked') by id. Then use the $.each function.
$(".mycheckbox").on("change", function() {
var message = [];
$('.mycheckbox:checked').sort(function(a, b) {
return parseInt(a.id) > parseInt(b.id);
}).each(function() {
var messagePart = $(this).attr('data-message');
message.push(messagePart);
});
$(".summary").html(message.join(", "));
});
DEMO:
http://jsfiddle.net/kom7hd5o/
Resource:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort
When using splice() the index the item is inserted to should be 0-indexed. For example:
var arr = [1,2,3,5,6];
arr.splice(3, 0, 4);
will insert 4 into the 3rd 0-indexed location.
Also, you need to use 0 as the 2nd parameter in splice when inserting a value like you want.
To make your code work you should change the id parameter of each input to be 0-indexed, and then use splice() to insert the item.
$(".mycheckbox").on("change", function() {
var message = [];
$('.mycheckbox:checked').each(function() {
var messagePart = $(this).attr('data-message');
message.splice($(this).attr('id'), 0,messagePart);
});
$(".summary").html(message.join(", "));
});
Here's a working example:
$(".mycheckbox").on("change", function() {
var message = [];
$('.mycheckbox:checked').each(function() {
var messagePart = $(this).attr('data-message');
message.splice($(this).attr('id'), 0,messagePart);
});
$(".summary").html(message.join(", "));
});
$("input:checkbox").on('click', function() {
// in the handler, 'this' refers to the box clicked on
var $box = $(this);
if ($box.is(":checked")) {
// the name of the box is retrieved using the .attr() method
// as it is assumed and expected to be immutable
var group = "input:checkbox[name='" + $box.attr("name") + "']";
// the checked state of the group/box on the other hand will change
// and the current value is retrieved using .prop() method
$(group).prop("checked", false);
$box.prop("checked", true);
} else {
$box.prop("checked", false);
}
});
.selection_area {
border: 1px solid gray;
margin-bottom: 10px;
padding: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="selection_area">
<h4>Select as many of these options as desired</h4>
<p>Should appear in numerical order</p>
<input type="checkbox" class="mycheckbox" id="1" data-message="Second" />Second
<br/>
<input type="checkbox" class="mycheckbox" id="0" data-message="First" />First
<br/>
<input type="checkbox" class="mycheckbox" id="3" data-message="Fourth" />Fourth
<br/>
</div>
<h5>Summary of Selections:</h5>
<div class="summary"></div>
Here's an updated JSFiddle.

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 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.

Categories

Resources