jQuery Appending Input elements - javascript

I am trying to create a simple Do to List which will have Checklists with a list of Tasks under it.
Idea is to create the Complete List and then Submit it to the Server to Save it in the Database.
I am looking to get the Input Boxes in a Clean structure like the following
Array
(
[checklist] => Array
(
[0] => Array
(
[task] => Array
(
[0] =>
[1] =>
)
)
[1] => Array
(
[task] => Array
(
[0] =>
[1] =>
[2] =>
)
)
[2] =>
)
[submit] => Submit
)
As i need to Add the right name to the input box to retain the structure i receive in the database i will need to count the Checklist number and the Task number and then append the same.
One unique case is when a user delete an input box from the middle of the list of tasks how can i retain the number to increment so that i do not over lap an input name and lose the data.
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>ToDo</title>
<script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
</head>
<body>
<form action="todo.php" method="post" name="todo">
<ul>
<li>
<input name="checklist[0]" type="text">
<ul>
<li>
<input name="checklist[0][task][0]" type="text">
</li>
<li>
<input name="checklist[0][task][1]" type="text">
</li>
</ul>
<a class="add" href="#">Add one</a> </li>
<li>
<input name="checklist[1]" type="text">
<ul>
<li>
<input name="checklist[1][task][0]" type="text">
</li>
<li>
<input name="checklist[1][task][1]" type="text">
</li>
<li>
<input name="checklist[1][task][2]" type="text">
</li>
</ul>
<a class="add" href="#">Add one</a> </li>
<li>
<input name="checklist[2]" type="text">
<ul>
</ul>
<a class="add" href="#">Add one</a> </li>
</ul>
<input name="submit" type="submit" value="Submit">
</form>
<script language="javascript">
$( ".add" ).click(function() {
// Find the Task Count
var task_count = $(this).siblings('ul').children('li').length;
var count = $(this).siblings('ul').count;
var input = '<li><input name="checklist[][task][]" type="text"></li>';
console.log(task_count);
$(this).siblings('ul').append(input);
});
</script>
<hr/>
<pre>
<?php
print_r($_POST);
?>
</pre>
</body>
</html>
Link: http://play.mink7.com/todo.php
The code (at the page bottom) is:
$( ".add" ).click(function() {
// Find the Task Count
var task_count = $(this).siblings('ul').children('li').length;
var count = $(this).siblings('ul').count;
var input = '<li><input name="checklist[][task][]" type="text"></li>';
console.log(task_count);
$(this).siblings('ul').append(input);
});

When user removes an input you can store the input name probably in an array. And while appending you can check the array for the name. Based on the absence or presence of the name in array you can rename newly appended input. This will prevent the data loss if any.
Another approach will be to don't bother about the names while appending. But before the form is submitted, you can dynamically generate the name of the inputs based on the children count and the task name. This will certainly prevent the data loss.
Here is the demo for the second method: http://jsfiddle.net/lotusgodkk/GCu2D/359/
$(document).ready(function () {
$('input[type="submit"]').on('click', function (e) {
$('form>ul').each(function () {
var ul = $(this);
var name = ul.attr('data-name');
var inputs = $('input', ul);
inputs.each(function () {
var i = $(this);
var index = inputs.index(i);
var n = name + '_' + index; // Generate the name of input
i.attr('name', n);
});
});
return false;
})
});
Sample HTML:
<form action="todo.php" method="post" name="todo">
<ul data-name="listone">
<li>
<input name="checklist[0]" type="text" />
<ul>
<li>
<input name="checklist[0][task][0]" type="text" />
</li>
<li>
<input name="checklist[0][task][1]" type="text" />
</li>
</ul> <a class="add" href="#">Add one</a>
</li>
<li>
<input name="checklist[1]" type="text" />
<ul>
<li>
<input name="checklist[1][task][0]" type="text" />
</li>
<li>
<input name="checklist[1][task][1]" type="text" />
</li>
<li>
<input name="checklist[1][task][2]" type="text" />
</li>
</ul> <a class="add" href="#">Add one</a>
</li>
<li data-name="listthree">
<input name="checklist[2]" type="text" />
<ul></ul> <a class="add" href="#">Add one</a>
</li>
</ul>
<input name="submit" type="submit" value="Submit" />
</form>
Here, for naming I used a data attribute on ul and the index on input inside the list.
Click on the submit button and you'll see the changed name of input.

I think you should count checklists and tasks at submit time. Just ignore the names during "edit time" and set the names all in one block at the end, like this:
http://jsfiddle.net/s3j7ok56/1/
This way if the user deletes, or moves (drag?) items, you just don't care as they will be named correctly at the end.
( example with remove: http://jsfiddle.net/s3j7ok56/2/ )
Note that I also set the val() of inputs for debug, to show the names. And I block the form submit for JsFiddle, all this should be removed to allow correct form posting.
HTML:
<form method="post" id="todo" name="todo" onsubmit="/* for JSFIDDLE */ return false;">
<ul id="all">
</ul>
<a id="addc" href="#">add checklist</a><br />
<input name="submit" type="submit" value="Submit">
</form>
JS:
$(function() {
$("#addc").click(function(e) {
var elem=$('<li class="checklist"><input type="text"><ul class="tasks"></ul></li>');
var link=$('<a class="add" href="#">Add task</a>');
link.appendTo(elem);
elem.appendTo("#all");
link.click(function(e1) {
var task=$('<li class="task"><input type="text"></li>');
$(this).parent().children(".tasks").append(task);
});
});
$("#todo").submit(function() {
var countLists=0;
var countTasks=0;
$("#all>li.checklist>input").each(function() {
$(this).attr("name","checklist["+countLists+"]");
$(this).val("checklist["+countLists+"]");
countTasks=0;
$(this).parent().find("ul.tasks>li.task>input").each(function() {
$(this).attr("name","checklist["+countLists+"]task["+countTasks+"]");
$(this).val("checklist["+countLists+"]task["+countTasks+"]");
countTasks++;
});
countLists++;
})
return true;
});
});

Related

Why is my javascript code duplicating li?

I am a Javascript beginner (this is my first javascript program) and I have a few problems with my mini app...
I am trying to build a page that allows you to choose who was in your team working with you today. The user should be able to build his own list among a list of names.
When the user clicks on "Add to the team", it should remove the corresponding <li> and add it to the selected list below.
The button needs to change from Add to the team to Delete
I am struggling to change the button textcontent if user choose to add then remove then add the same <li>...
I've been trying a lot of things, this is my last try:
'script type="text/javascript"';
var selected = document.querySelector('#selected-list ul');
var team = document.querySelector('#team-list ul');
var searchBar = document.forms['search-employees'].querySelector('input');
//add to the selected team
team.addEventListener("click", function(e){
if(e.target.className == 'add'){
const li = document.createElement('li');
const employeename = document.createElement('span');
const deleteBtn = document.createElement('span');
//add content
deleteBtn.textContent = 'add';
employeename.textContent = e.target.parentElement.firstElementChild.textContent;
//add classes
employeename.classList.add("name");
deleteBtn.classList.add('delete');
// append to document
li.appendChild(employeename);
li.appendChild(deleteBtn);
selected.appendChild(li);
console.log(deleteBtn);
}
})
//delete teammate from selected team
selected.addEventListener('click', function(e){
if(e.target.className == 'delete'){
const li = document.createElement('li');
const employeename = document.createElement('span');
const addBtn = document.createElement('span');
//add content
addBtn.textContent = 'delete';
employeename.textContent = e.target.parentElement.firstElementChild.textContent;
//add classes
employeename.classList.add("name");
addBtn.classList.add('add');
// append to document
li.appendChild(employeename);
li.appendChild(addBtn);
team.appendChild(li);
//delete from selected
console.log(addBtn);
}
})
//add a new employee - listen to submit event from form
var addForm = document.forms['add-employee'];
addForm.addEventListener('submit', function(e){
e.preventDefault(); //prevent default behavior
const value = addForm.querySelector('input[type="text"]').value;
console.log(value);
//create elements
const li = document.createElement('li');
const employeename = document.createElement('span');
const deleteBtn = document.createElement('span');
//add content
deleteBtn.textContent = 'delete';
employeename.textContent = value;
//add classes
employeename.classList.add("name");
deleteBtn.classList.add('delete');
// append to document
li.appendChild(employeename);
li.appendChild(deleteBtn);
selected.appendChild(li);
//apply style
})
//filter names
//grab a reference to the form
searchBar.addEventListener('keyup', function(e){
//term the user is searching
const term = e.target.value.toLowerCase();
//names to compare
const names = team.getElementsByTagName('li');
Array.from(names).forEach(function(name){
const fullname = team.firstElementChild.textContent;
//check if name exists
if(fullname.toLowerCase().indexOf(term) != -1){
name.style.display = 'block';
} else {
name.style.display = 'none';
}
})
})
It gives me the following result:
Every time I hit the button, it gives me a duplicate (same for the input Teammate not found)
Moreover, I still can't, once deleted, get back to a "Add to the team"...
I hope you guys can enlighten me, I spent maybe too much time on it, but I cant find out right now...
This is few captions of what it does:
enter image description here
once you clicked on delete in selected list
enter image description here
Thank you
HTML:
<?php
require_once 'core/init.php';
include 'includes/checkedboxes.php';
include 'includes/headerfront.php';
//include_once 'includes/dbh.inc.php';
if(Session::exists('Success')){
echo Session::flash('Success');
}
?>
<html>
<head>
<link rel="stylesheet" href="styleChief.css">
</head>
<body>
<section class="team">
<div id="wrapper">
<div id="container-left">
<div id="search">
<h2 class="title">Who was in your team today?</h1>
<form id="search-employees">
<input type="text" name="search" placeholder="Search a name..">
</form>
</div>
<div id="team-list">
<h3 class="title">Team list</h3>
<p>Select today's teammates</p>
<ul>
<li>
<span class="name">name</span>
<span class="add">Add to the team</span>
</li>
<li>
<span class="name">name 1</span>
<span class="add">Add to the team</span>
</li>
<li>
<span class="name">name 2</span>
<span class="add">Add to the team</span>
</li>
<li>
<span class="name">name 3</span>
<span class="add">Add to the team</span>
</li>
</ul>
</div>
<div id=newmember class="newmember">
<h4>
<a class="not-found" href="#"><img class="img" src="img/not-found.png" width="20" height="20" alt="not-found">
</a>Teammate not found?</h4>
<form id="add-employee">
<h3 class="title">Add a new member:</h3>
<input type="text" placeholder="New teammate name">
<button>Add</button>
</form>
</div>
</div>
<div id="container-right">
<h2>Selected</h2>
<div id="selected-list">
<h3 class="title">You have selected the following teammates for today: </h3>
<ul>
</ul>
</div>
</div>
</div>
</section>
<section class="part">
<h2>Which part(s) have you been working on today?</h2>
<input type="checkbox" name="checklist-part" value="Decoratives"><label>Decoratives</label>
<input type="checkbox" name="checklist-part" value="Windows"><label>Windows</label>
<input type="checkbox" name="checklist-part" value="Signage Gibela"><label>Signage Gibela</label>
<input type="checkbox" name="checklist-part" value="Signage Prasa"><label>Signage Prasa</label>
<input type="checkbox" name="checklist-part" value="Stripes"><label>Stripes</label>
<input type="checkbox" name="checklist-part" value="Other"><label>Other</label><br/>
<input type="submit" name="submit" value="Continue" /><br/>
</form>
</section>
<?php
$sql="SELECT * FROM dttechnames;";
$result=mysqli_query($conn,$sql);
?>
<script src="app/app.js"></script>
<script src="app/app.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
</body>
</html>
I tried to fx a few issues with your snippet (e. g. there was a <form> tag missing). Basically, you were working far too hard in your script part. If you want to move a <li> from one <ul> to another then it is easiest to simply .appendChild() it to the target <ul>. Doing so will automatically remove it from its original parent <ul>. As the "move" operation is universal to all team-member-<li>s - whether they are part of the "team" or the "selected" group - we can use a single "click" event-listener for all of them. I added it to the outer #wrapper div.
The following snippet only covers the team member picking part (I removed all other script components for clarity) but it should demonstrate the basic points:
var grps=['#selected','#team'].map(s=>document.querySelector(s+'-list ul')),
btn=['Add to the team','Remove from the team'];
[...grps[1].querySelectorAll('.move')].forEach(sp=>sp.textContent=btn[0])
// move members ...
document.querySelector('#wrapper').addEventListener("click", function(e){
if(e.target.classList.contains('move')){
var i=btn.indexOf(e.target.textContent); // i=0 (Adding) or i=1 (Removing) ?
e.target.textContent=btn[1-i]; // exchange button caption
grps[i].appendChild(e.target.parentNode) // move team member ...
}
})
li {margin: 10px}
.move{
float: right;
background: #9361bf;
padding:4px;
border-radius: 3px;
}
<section class="team">
<div id="wrapper">
<div id="container-left">
<div id="search">
<h2 class="title">Who was in your team today?</h1>
<form id="search-employees">
<input type="text" name="search" placeholder="Search a name..">
</form>
</div>
<div id="team-list">
<h3 class="title">Team list</h3>
<p>Select today's teammates</p>
<ul>
<li>
<span class="name">Roman BARON</span>
<span class="move"></span>
</li>
<li>
<span class="name">Vincent Houdeville</span>
<span class="move"></span>
</li>
<li>
<span class="name">Jayson Abrams</span>
<span class="move"></span>
</li>
<li>
<span class="name">Bafana Hlongwane</span>
<span class="move"></span>
</li>
</ul>
</div>
<div id=newmember class="newmember">
<h4>
<a class="not-found" href="#"><img class="img" src="img/not-found.png" width="20" height="20" alt="not-found">
</a>Teammate not found?</h4>
<form id="add-employee">
<h3 class="title">Add a new member:</h3>
<input type="text" placeholder="New teammate name">
<button>Add</button>
</form>
</div>
</div>
<div id="container-right">
<h2>Selected</h2>
<div id="selected-list">
<h3 class="title">You have selected the following teammates for today: </h3>
<ul>
</ul>
</div>
</div>
</div>
</section>
<section class="part">
<h2>Which part(s) have you been working on today?</h2>
<form id="parts">
<label><input type="checkbox" name="checklist-part" value="Decoratives">Decoratives</label>
<label><input type="checkbox" name="checklist-part" value="Windows">Windows</label>
<label><input type="checkbox" name="checklist-part" value="Signage Gibela">Signage Gibela</label>
<label><input type="checkbox" name="checklist-part" value="Signage Prasa">Signage Prasa</label>
<label><input type="checkbox" name="checklist-part" value="Stripes">Stripes</label>
<label><input type="checkbox" name="checklist-part" value="Other">Other</label><br/>
<input type="submit" name="submit" value="Continue" /><br/>
</form>
</section>
This seems to have been the first question you posted on StackOverflow, so a belated: "Welcome here!"
But I would like to point out that your question was unnecessarily long and complicated. You should try and focus on one point per question. This would make it much more accessible for other Stackoverflow members to answer without having to review large chunks of code first.
And one final remark: You tagged your question with jQuery, but as you haven't used it in your script I also removed the script src="...jquery..."></script> tag from my snippet. I am eternally grateful to John Resig for giving us jQuery but in modern browsers you can now mostly do without it.
After trying cars10m solution, I have few problems..
1. The css style of my "Add to the team" disappeared. I of course changed my code above to:
.add,.delete {
float: right;
background: #9361bf;
padding:6px;
border-radius: 4px;
}
to :
.move{
float: right;
background: #9361bf;
padding:6px;
border-radius: 4px;
}
but doesnt style the class.
Maybe move is a reserved keyword?
Anyways, I have another problem:
2. That solution moves the selected "li", but inside the same <ul>.
When I do a console.log(e.target.textContent) just after if(e.target.classList.contains('move')), i get to see that it contains "Add to the team" and "Remove from the team".
I found out that it was behaving as if I clicked two twice, but I only clicked once.
Why?
Thank you guys for your answers!!

Retrieving the values from input elements and storing in an array

I've got a form that takes input from the user
<form id='myForm'>
<div id='x'>
<h2> start </h2>
<ul class="rounded">
<li><input type="text" placeholder="text" id="o" /></li>
</ul>
<h2>dests </h2>
<ul class="rounded">
<li><input type="text" placeholder="text" id="d" /></li>
</ul>
<ul class="rounded">
<li><input type="text" placeholder="text" id="d" /></li>
</ul>
</div>
<li class="arrow"><a href="#page2" onclick='function()'>Run </a></li>
</form>
I need a way of getting the user input from every field in the form, and placing it into an array. I have looked into getElementByTagName('input'), but this returns a HTMLCollection object. Any suggestions? (P.S i'm using a jqtouch if you're wondering what's up with the weird syntax)
You can use Array.prototype.map to create an array from the list of input elements obtained from querySelectorAll.
Try filling the inputs and clicking Run in the demo below:
var elements = document.querySelectorAll('#myForm input');
function callme() {
var result = Array.prototype.map.call(elements, function(e) {
return e.value;
});
console.log(result);
}
<form id='myForm'>
<div id='x'>
<h2> start </h2>
<ul class="rounded">
<li>
<input type="text" placeholder="text" />
</li>
</ul>
<h2>dests </h2>
<ul class="rounded">
<li>
<input type="text" placeholder="text" />
</li>
</ul>
<ul class="rounded">
<li>
<input type="text" placeholder="text" />
</li>
</ul>
</div>
<ul>
<li class="arrow"><a href="#page2" onclick='callme()'>Run </a>
</li>
</ul>
</form>
As others have mentioned be careful to use the html id attribute with a unique id, i.e. each input should have its own.
Using vanilla JavaScript, document.getElementsByTagName() returns a live html collection and you can access its members as properties using [index] to get the element you want. Then use textObject.value to access the inputs' value.
All in all, document.getElementsByTagName('input')[0].value will provide the value of the first input! That is the logic, also check the snippet.
Please also consider the following:
element.querySelectorAll() is generally slower than element.getElementsByTagName(), as the first uses a depth-first pre-order traversal of the document's nodes
element.querySelectorAll() returns a StaticNodeList
I found this article quite interesting for this topic.
function retrieve(){
let list = document.getElementById('inputListContainer');
let input = list.getElementsByTagName('input');
let array = [];
for( let i = 0; i < input.length; i++ ){
//input[i].value is the same as document.getElementsByTagName('input')[i].value
array.push(input[i].value);
}
console.log( array );
}
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div id='inputListContainer'>
<!-- Using a single ul to parent list items. Note that this does not affect the script -->
<ul id='inputList' class='rounded'>
<li><input type="text" placeholder="one"/></li>
<li><input type="text" placeholder="two"/></li>
<li><input type="text" placeholder="three"/></li>
</ul>
<button onclick='retrieve()'>Retrieve</button>
</div>
</body>
</html>
Try this:
function getValues() {
var values = []; // Array of input values
var elements = document.querySelectorAll("#myForm input");
for(var i = 0; i < elements.length; i++) {
values.push(elements[i].value);
//If you need the input ID:
//values.push({name: elements[i].id , value: elements[i].value});
}
}
For this you can use Document.querySelectorAll()
Returns a list of the elements within the document (using depth-first pre-order traversal of the document's nodes) that match the specified group of selectors. The object returned is a NodeList.
Using document.querySelectorAll("#myForm input"); will target all inputs within the form with the ID of myForm.
Then a for() loop is used to iterate through the collection and push the input values into the array .
The for statement creates a loop that consists of three optional expressions, enclosed in parentheses and separated by semicolons, followed by a statement (usually a block statement) to be executed in the loop.
for ([initialization]; [condition]; [final-expression])
statement
function BuildArray() {
var myArray = [];
var input = document.querySelectorAll("#myForm input");
for (var i = 0; i < input.length; i++) {
myArray.push(input[i].value);
}
console.log(myArray);
}
<form id='myForm'>
<div id='x'>
<h2> start </h2>
<ul class="rounded">
<li>
<input type="text" placeholder="text" id="o" value="first" />
</li>
</ul>
<h2>dests </h2>
<ul class="rounded">
<li>
<input type="text" placeholder="text" id="d" value="second" />
</li>
</ul>
<ul class="rounded">
<li>
<input type="text" placeholder="text" id="d" value="third" />
</li>
</ul>
</div>
<li class="arrow"><a href="#page2" onclick='BuildArray()'>Run </a>
</li>
</form>
I would also like to recommend keeping ID's unique if ID's are required but for this task ID's are not used in the selector so no problems if ID's are the same.
If you have any questions about the source code above please leave a comment below and i will get back to you as soon as possible.
I hope this helps. Happy coding!
You just need to iterate through each input and push each value into an array. You would call something like this on click. See jQuery example here.
function click() {
var arr = [];
$.each($('input'), function(k,v) {
arr.push($(v).val());
})
console.log(arr);
}

How to Fill value= section of form from another section of webpage?

So, right now I have this small unordered list.
<ul id="sortable2" class="connectedSortable">
<li id="litem1" class="ui-state-highlight">A Comfortable Life</li>
<li id="litem2" class="ui-state-highlight">An Exciting Life</li>
</ul>
Then, I have series of hidden inputs in a form for sending information to the next page.
<form action="Instrumental_Values1.php" method="POST">
<input type="hidden" name="item1" value="<script getElementById('litem1').innerhtml();></script>"/>
<input type="hidden" name="item2" value="<script getElementById('litem2').innerhtml();></script>"/>
</form>
My problem is that my bit of code to try to grab the list item values by ID and make the them equal to "value" in the hidden inputs doesn't work. I need to transfer those list items and make them the "value" in the hidden input.
So essentially, the next page is a php file that is just echoing those values back, like so:
<?php
$val1=$_POST['item1'];
$val2=$_POST['item2'];
echo $val1.' '.$val2;
?>
Does anyone know what I'm doing wrong or have an example to share? I have to use PHP to do this, a Javascript solution is not tenable.
This should work.
I've used .val().
Reference: jQuery Documentation
Add ids to the inputs:
<form action="Instrumental_Values1.php" method="POST">
<input type="hidden" id="item1" name="item1" value="" />
<input type="hidden" id="item2" name="item2" value="" />
</form>
Add this script to your page:
<script>
$("#item1").val($("#litem1").text());
$("#item2").val($("#litem2").text());
</script>
It looks like you're using classical javascript here, so following that style this might work:
<ul id="sortable2" class="connectedSortable">
<li id="litem1" class="ui-state-highlight">A Comfortable Life</li>
<li id="litem2" class="ui-state-highlight">An Exciting Life</li>
</ul>
<form id="theForm" action="Instrumental_Values1.php" method="POST">
<input type="hidden" id="formItem1" name="item1" value="" />
<input type="hidden" id="formItem2" name="item2" value="" />
</form>
<script>
//Set Form Value 1
var formItem1 = document.getElementById("formItem1");
formItem1.value = document.getElementById("litem1").innerHTML;
//Set Form Value 2
var formItem2 = document.getElementById("formItem2");
formItem2.value = document.getElementById("litem2").innerHTML;
//Auto submit the form
document.getElementById("theForm").submit();
</script>
The idea here is to set your form values in a script tag instead of trying inline JavaScript. From your original code, it looks like the values in your form would have been a string in the form of '<script getElementById('litem1').innerhtml();></script>' instead of the actual list value. Also, I didn't know how you where sending your form so the last line in the script tag will automatically send the form.
You dont't need to add ids or names to the elements and you need only one ul. The script will do that for you.
How it works
It simply writes the content of the li items in an array when the order changes and then writes the content to the hidden inputs.
<body>
<ul id="sortable" class="connectedSortable">
<li class="ui-state-highlight">A Comfortable Life</li>
<li class="ui-state-highlight">An Exciting Life</li>
<li class="ui-state-highlight">A Sense of Accomplishment</li>
</ul>
<form id="sortable-form" action="test.php" method="POST">
<input type="hidden" value="" />
<input type="hidden" value="" />
<input type="hidden" value="" />
<br />
<input type = "submit" value = "Next Page">
</form>
</html>
<script>
$(document).ready(function() {
// ADD IDS TO LI
var litem_id = 1;
$("#sortable li").each(function(){
$(this).attr('id', "litem" + litem_id);
litem_id++;
});
// ADD IDS AND NAMES TO INPUTS
var item_id = 1;
$("#sortable-form input[type='hidden']").each(function(){
$(this).attr('id', "item" + item_id);
$(this).attr('name', "item" + item_id);
item_id++;
});
$( "#sortable" ).sortable({
connectWith: "#shopping-cart"
});
$( "#sortable" ).sortable({
stop: function( event, ui ) {
var values = [];
$("#sortable li").each(function(){
// SAVE ITEMS IN ARRAY
values.push($(this).text());
});
var i = 0;
$("#sortable-form input[type='hidden']").each(function(){
// WRITE ITEMS TO INPUTS
$(this).val( $(values).get(i) );
i++;
});
}
});
});
</script>

Submit filter form on link click

I'm trying to make something a bit like this:
This is my code: http://jsfiddle.net/928Dj/19/
$("ul.opt").addClass("hidden");
$('#filter > li > a').on("click", function (e) {
var cache = $(this).next('ul');
$('#filter ul:visible').not(cache).hide();
cache.toggle();
});
I'm trying to make it degradable so without javascript they can submit the form to adjust the results, but with javascript they can just click the text of the desired result.
Question A
How can I make it so by them clicking the text alone, with javascript enabled, it not only selects the radio button but also submit the form.
Question B
Is my code the right approach to achieve this desired outcome?
Replace the radio buttons with submit buttons.
<input type="submit" name="status" value="Status 1">
i think google uses <a> tag instead <input> and (but i'm not sure) catches the click and makes a ajax call to update only the result (without any form)... like: http://jsfiddle.net/928Dj/25/
HTML, change <input> in <a>:
Status 1
JS
$('ul.opt a').click(function(e){
e.preventDefault();
$(this).parents(".opt").find("a").removeClass("active");
$(this).addClass("active");
$.get($(this).attr("href"),function(res){
//do something with response
});
});
On <a> click the JS simply perform search.action (or other search service) with sortDate=status1 like parameter via AJAX, for sort the result.
You can concat the sorting parameters status=status1&date=date1 for multiple sorting.
I don't know if there are any ways to perform the submit without using javascript (and without reload all page).
I've updated your fiddle with submit buttons that are hidden if javascript is enabled.
<div>
<form action="/echo/html/">
<ul id="filter">
<li> Any status ▾
<ul class="opt">
<li>
<label>
<input type="radio" name="status" />Status 1</label>
</li>
<li>
<label>
<input type="radio" name="status" />Status 2</label>
</li>
<li>
<input type="submit" value="submit"/>
</li>
</ul>
</li>
<li> Any date ▾
<ul class="opt">
<li>
<label>
<input type="radio" name="date" />Date 1</label>
</li>
<li>
<label>
<input type="radio" name="date" />Date 2</label>
</li>
<li>
<input type="submit" value="submit"/>
</li>
</ul>
</li>
</ul>
</form>
</div>
<div id="results">
Filtered results go here
</div>
<script>
$("ul.opt").addClass("hidden");
$('#filter > li > a').on("click", function (e) {
var cache = $(this).next('ul');
$('#filter ul:visible').not(cache).hide();
cache.toggle();
$('#filter li input[type=submit]').hide();
});
$('#filter input[type=radio]').click(function() {
var $form = $(this).closest('form');
$('#results').html('filtering...');
$.post($form.attr('action'),$form.serialize(),function(response) {
if ( response ) {
$('#results').html(response);
} else {
$('#results').html('no results found');
}
});
});
</script>

To get the letter when i click on the that letter

I have tab which have A-Z letters. for that i wrote this
<div id="tabs">
<ul>
<li>By First Name</li>
</ul>
<div id="tabs-1">
<ul class="find-agent">
<?php for ($char=65; $char < 91; $char++ )
echo '<li>'.chr($char).'</li>';?>
<form id="members-search" action="members">
<input type="text" name="q" size="100" style=" margin: 0; "/>
<input type="submit" value="Search" placeholder="Type a Agent Name" class="btn btn-primary"/>
</form>
</ul>
</div>
</div>
Now i want to get the letter, when i click on the letter. Is that possible in that way or i have to use get method to get the letter which is clicked.
If you want to get the letter using only PHP then $_GET or $_REQUEST will be your method. Other than this you could look at adding a click event to the link using something like jquery which would give you the letter client side.
Whatever page is at /members/ (hopefully a php page) you should be be able to access the letter (filter) with $_GET['filter'] or $_REQUEST['filter']
$('.find-agent').on('click', 'li', function() {
var letter = $(this).text();
// Do whatever you want with the letter
alert(letter);
});
DEMO: http://jsfiddle.net/BudZ2/2
I suggest using JQuery Ajax to send a GET request to your "members" page. This way you can pre-check what letter was clicked before sending it to the server and you get to load your list of names dynamically instead of having to reload the whole page.
<script type="text/javascript">
$(document).ready(function() {
$(".alphabet").click(function(){
var selected_letter= $(this).text());
/* if you want to do something with this letter before sending it to the
* server here is your chance.
*/
$.ajax({
type: "GET",
url: 'your_site/members/?filterby=first_name&filter='+selected_letter,
success: function (list_of_names) {
// do something with this list
}
});
});
});
</script>
<div id="tabs">
<ul>
<li>By First Name</li>
</ul>
<div id="tabs-1">
<ul class="find-agent">
<?php for ($char=65; $char < 91; $char++ )
echo '<li class="alphabet">'.chr($char).'</li>';?>
<form id="members-search" action="members">
<input type="text" name="q" size="100" style=" margin: 0; "/>
<input type="submit" value="Search" placeholder="Type a Agent Name" class="btn btn-primary"/>
</form>
</ul>
</div>
</div>

Categories