To get the letter when i click on the that letter - javascript

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>

Related

How to stop my page from reseting after the page is submited

I have a code, who helps me switch between forms, however, when I submit the form, the page will reset and display first(default) tab again. Could anyone help me understand how I can make it so the tab I submit the form from stays there if the submision fails or even if the submision was successfull?
Forms are switching using a little JS code and are submited from a PHP POST method form.
Please find the code below:
Javascript responsible for switching between tabs:
function onTabClick(event) {
let activeTabs = document.querySelectorAll('.active');
// deactivate existing active tab
for (let i = 0; i < activeTabs.length; i++) {
activeTabs[i].className = activeTabs[i].className.replace('active', '');
}
// activate new tab
event.target.parentElement.className += 'active';
document.getElementById(event.target.href.split('#')[1]).className += 'active';
}
const elements = document.getElementsByClassName('nav-tab-element');
for (let i = 0; i < elements.length; i++) {
elements[i].addEventListener('click', onTabClick, false);
}
CSS:
.tab-content {
display: none;
}
.tab-content.active {
display: block;
}
And here is the HTML forms:
<body>
<header>
<h1 class="main-header">
Add a New Product
</h1>
</header>
<main>
<ul id="nav-tab" class="nav">
<li class="active">
<a class="nav-tab-element" href="#books">Books</a>
</li>
<li>
<a class="nav-tab-element" href="#dvds">DVD's</a>
</li>
<li>
<a class="nav-tab-element" href="#furniture">Furniture</a>
</li>
</ul>
<form method="POST">
<div class="tab-content active" id="books">
<div class="book-tab">
<input type="text" name="sku" placeholder="test form for books" autocomplete="off">
</div>
<div class="btn">
<input type="submit" value="Submit">
</div>
</div>
</form>
<form method="POST">
<div class="tab-content " id="dvds">
<div class="dvd-tab">
<input type="text" name="sku" placeholder="test form for DVD" autocomplete="off">
</div>
<div class="btn">
<input type="submit" value="Submit">
</div>
</div>
</form>
<form method="POST">
<div class="tab-content " id="furniture">
<div class="furniture-tab">
<input type="text" name="sku" placeholder="test form for furniture" autocomplete="off">
</div>
<div class="btn">
<input type="submit" value="Submit">
</div>
</div>
</form>
</main>
<script src="main.js"></script>
</body>
Clicking submit submits the form data to the page given in the action attribute in form. If you don't put this attribute in (as you have not done) the default is to submit to the current page.
To fix the issue you have, I would suggest that rather than using vanilla form submit, you do you submission via ajax. Making an ajax call is quite simple in jQuery, so I recommend you look into that.
There is an event that is triggered when you send a form. You can prevent your page to reload doing the following:
event.preventDefault()
you can find more about here: https://www.w3schools.com/jsref/event_preventdefault.asp
or here https://www.w3schools.com/jquery/event_preventdefault.asp
All you have to do is add event.preventDefault() to the first line of your onTabClick(event) function. After you preventDefault you can run whatever logic you want right there.
The way vanilla html/js interact is: On form submission, the page attempts to send the info to a server and then it refreshes to update with new information. The rise of SPAs has shifted the desired behavior, and you need to override the browser default behavior to stop the refresh.
Adding Ajax/Axios would work as most of those API libraries have built in functions to override the default, but it is not necessary.

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>

jQuery Appending Input elements

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

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>

two forms, two divs, appending data from only one form to only one div?

I have a slider with two slides, both containing an identical form. When I submit from one or the other form, I want to append the data from that form into the slide containing the form. I can obtain data from only one form, but I just can't get the append to only work on one slide. It always adds to both. I can't just use different IDs because I will be using ajax to change the non-visible slide based on forward or back slide navigation so the slider is theoretically infinite.
Here is my html (simplified for easier viewing):
<div class="flexslider">
<ul class="slides">
<li>
<ul class="table">
<li>
<div class="clearfix">
<span class="nameSpan">Customer One</span>
</div>
</li>
</ul>
<form class="addNewCustomerForm" method="post">
<h1>Add New Customer</h1>
<input type="text" name="customerName" id="customerName">
<input class="button" type="submit" value="Add New Customer">
</form>
</li>
<li>
<ul class="table">
<li>
<div class="clearfix">
<span class="nameSpan">Customer One</span>
</div>
</li>
</ul>
<form class="addNewCustomerForm" method="post">
<h1>Add New Customer</h1>
<input type="text" name="customerName" id="customerName">
<input class="button" type="submit" value="Add New Customer">
</form>
</li>
</ul>
</div>
And here is my javascript (Again, simplified):
$(".addNewCustomerForm").submit(function(event) {
$.post('addNewCustomer.asp', $(this).serialize(), function(result){
$(".table", this).append(result);
$(".newLine").slideDown();
})
return false;
});
You probably want something like this
$(".addNewCustomerForm").submit(function(event) {
var thisForm = $(this);
$.post('addNewCustomer.asp', $(this).serialize(), function(result){
thisForm.parent().find('.table').append(result);
$(".newLine").slideDown();
})
return false;
});
(tested it locally, changed first to find)
That's because $(".table", this) matches both slides.
You can solve this by giving each slide and id, like id="slide1"
Then do $("#slide1") (or slide2) depending on which was submitted.
You basically need the bind the form to the slide, since each slide has it's own form.
Similarly you might need to do a similar thing for $(".addNewCustomerForm"). Give each form a unique id and bind one submit handler to #slide1, and the other to #slide2

Categories