I am currently working with jquery ui tabs and ajax/post submit without page refresh. With some guidance I have been able to get the div #wmd-preview submited when clicking the next button. The issue is that I also have other fields I will like to submit at the same time when the next button is clicked in various tabs.
How can I submit the input values of various input fields in different tabs when clicking the next button? EXAMPLE
(for some testing i currently have the other input fields submit with keyup and timer setup)
JS- NEXT/Previous button merged with submit/ajax
<script>
var currentTab = 0;
$(function() {
var $tabs = $('#tabs').tabs({
disabled: [0, 1, 2]
, select: function() {
if (currentTab == 0) {
$.ajax({
type: "POST",
url: "test1.php",
data: { "wmdVal": $("#wmd-preview").html() },
success: function(result) {
$('#wmd_result').html( $('#resultval', result).html());
}
});
}
}
, show: function(event, ui) {
currentTab = ui.index;
}
});
$(".ui-tabs-panel").each(function(i) {
var totalSize = $(".ui-tabs-panel").size() - 1;
if (i != totalSize) {
next = i + 2;
$(this).append("<a href='#' class='next-tab mover' rel='" + next + "'>Next Page »</a>");
}
if (i != 0) {
prev = i;
$(this).append("<a href='#' class='prev-tab mover' rel='" + prev + "'>« Prev Page</a>");
}
});
$('.next-tab, .prev-tab').click(function() {
var tabIndex = $(this).attr("rel");
$tabs.tabs('enable', tabIndex)
.tabs('select', tabIndex)
.tabs("option","disabled", [0, 1]);
return false;
});
});
</script>
HTML
<div id="tab-1" class="ui-tabs-panel ui-tabs-hide">
<label for="title">Title</label>
<input type="text" id="title" name="title" size="60" autocomplete="off" value="<? $title ?>"/>
<div id="wmd-editor" class="wmd-panel">
<div id="wmd-button-bar"></div>
<textarea id="wmd-input" name="wmd-input"></textarea>
</div>
<div id="wmd-preview" class="wmd-panel"></div>
<div id="wmd_result"></div>
<div id="title_input"style="padding:20px;"></div>
</div>
<div id="tab-2" class="ui-tabs-panel ui-tabs-hide">
<label for="name">Name</label>
<input type="text" id="name" name="name" size="60" autocomplete="off" value="<? $name ?>"/>
<div id="name_input"></div>
</div>
PHP
<?
if (isset($_POST['title'])){
$wmdVal = $_POST['title'];
echo ('<div id="title_input"><span id="resultval"><h2>Title Echo result:</h2>'.$wmdVal.'</span></div>');
}
if (isset($_POST['wmdVal'])){
$wmdVal = $_POST['wmdVal'];
echo ('<div id="wmd_result"><span id="resultval"><h2>Description Echo result:</h2>'.$wmdVal.'</span></div>');
}
if (isset($_POST['name'])){
$name = $_POST['name'];
echo ('<div id="name_input"><span id="resultval"><h2>Description Echo result:</h2>'.$name.'</span></div>');
}
?>
As far as i know , there's no matter if the fields are in tabs or hidden ,
as long as they have ID , you can get them.
When using , for instance: $('#bla').val() , it will search the whole page until it will find an element with the ID "bla".
Therefore , just add it to the data option, like that:
{key1: 'value1', key2: 'value2'}
Try:
data: { "wmdVal": $("#wmd-preview").html() , "name": $("#name").val() , "title": $("#title").val() },
Should work (not been tested)
UPDATE:
After looking at your site's source code I think I found the problem.
From the results of clicking the next button you can understand that there's a $_POST['title'] variable (isset) , however it's empty.
So there's a problem in the ajax request,
This line:
"title": $("#title").html()
You're not looking for the html() of that input field.
You're looking for val().
Change the line above to:
"title": $("#title").val()
Should work now, update me if not
If you want to run the AJAX POST whenever you change the tab. You have to remove this condition: if(currentTab == 0){. Because this one is forcing the code to run, just when the first TAB is selected.
Besides that, you can post any data that you want. You just need to pass them to "data:" properties of the ajax. And Since they are global and uniques, you can call any of them by their IDs. Like that:
data:{
param1: $("#input1").val(),
param2: $("#input2").val(),
paramHtml1: $("#elementHtml1").html()
}
"title": $("#title").html() should be
"title": $("#title").val() -> you want the value of the field in question. This will send the correct value to the server.
It sort of seems like now you are asking why nothing is being printed in the 'Title Echo result:' area.
I think a good next step might be:
success: function(result) {
// fill title_input with the result of the ajax call
$('#title_input').html(result);
}
That will give you some output, but I think probably not the output you want. Maybe respond with what content you want in the 'title echo area'
Related
I have this script below that sends only 1 value to the requested URL, but now I need to adjust it to accept 2, I couldn't find a way to do that.
Each checkbox is accompanied by an input hidden named #note, I need to pass this #note value (that's my order ID) together.
$('#importaNF').click(function(){
var checkbox = $('.import_checkbox:checked');
if(checkbox.length > 0)
{
var checkbox_value = [];
$(checkbox).each(function(){
checkbox_value.push($(this).val());
});
$.ajax({
url:"<?php echo base_url(); ?>adm/pedidos/importaNF",
method:"POST",
data:{checkbox_value:checkbox_value},
success:function()
{
$('.removeRow').fadeOut(1500);
}
})
}
else
{
alert('Select atleast one records');
}
}
My HTML
<div class="btn-group">
<input type="checkbox" class="import_checkbox" name="import_checkbox" value="<?= $registro->NUMERO ?>">
<input type="input" id="note" class="import_input" name="import_input" value="<?= $registro->FATURA ?>" style="visibility:hidden">
</div>
I may be misinterpretting, but you can just extract it like you did the checkbox value and add a second property to the data object:
data:{checkbox_value:checkbox_value, note_value: note_value},
Unless you mean you're trying to pass a second url parameter?
Right now I am displaying a question and its possible answers in a modal on my page (shown below). The "submit answer" button will post the form but I can't use it in my situation (I explain this at the bottom of this post) so please ignore it.
I use the HTML & PHP code below to do retrieve the question and answers from my database.
<!-- The Modals -->
<div id="myModal" class="modal">
<!-- Modal content -->
<div class="modal-content">
<div class="modal-header">
<!-- display question as heading -->
<?php
while ( $row = $result->fetch_assoc() ) {
echo "<h3>" . $row[ "question" ] . "</h3>";
}
?>
<button id="close1" class="close">×</button>
</div>
<div class="modal-body">
<form action="#" method="post" id="quiz">
<!-- display answers as radio -->
<div>
<?php
while ($id = $choice_idResult1->fetch_assoc()) {
echo '<input type= "radio" name="question1_answers" id="question1_answers_A" value= "' . $id["choice_id"] . '"';
}
?>
<label for="question1_answers_A">
<?php while($row = $result2->fetch_assoc()) {echo $row["choice_text"];}
$answer1 = $row;
?>
</label>
</div> .....
When the "Open Modal 2" button is clicked, the JavaScript code below closes the modal and opens the next.
btn2.onclick = function() {
checkRadio('question1_answers_B');
modal.style.display = "none";
modal2.style.display = "block";
}
As you can see, I've called a function called checkRadio and passes it the id of the radio input that is the correct answer.
checkRadio then uses an if statement to check whether that radio is checked and if it is it calls another function that increments a variable tally.
var tally = 0;
function checkRadio(id) {
if (document.getElementById(id).checked) {
addTally();
}
}
function addTally() {
tally++;
}
I then have a function called showTally that I want to display the tally in the header of the next modal (for testing purposes). However, nothing shows up in the next modal no matter what I select.
function showTally() {
document.getElementById("tally").innerHTML = tally;
}
And in the modal header:
<h3 id="tally"></h3>
In plain English, I need to be able to identify which radio input has been selected by the user so that I can check it is the correct answer and add to the tally which will be displayed after the last question.I can't actually post the form as it will close the modal.
If you need more screenshots or information please let me know.
You can use localStorage or sessionStorage, it can save info to the session, the info exists when you refresh or redirect html page (same domain).
Here is usage below:
var tally = localStorage.getItem('tally') || 0
function addTally() {
tally++;
localStorage.setItem('tally', tally)
}
I may be misunderstanding the question, but this may help you.
var myAnswers1 = document.querySelector("question1_answers");
for(var i=0;i<myAnswers1.length;i++)
{
console.log("Question 1, radio index " + i + " is " + myAnswers1[i].checked + ".");
}
Sample Output:
Question 1, radio index 0 is false.
Question 1, radio index 1 is true.
Question 1, radio index 2 is true.
I am trying to submit a form with dynamic inputs. I am able to add a several inputs via the javascript. However, when I submit, it only picks up the first added input value. I hope someone can take a look at this for me as I've tried to fix this for so long. Thank you
Controller
public function update(){
$this->form_validation->set_rules('first_name', 'Firstname', 'trim|required|xss_clean');
$this->form_validation->set_rules('last_name', 'Lastname', 'trim|required|xss_clean');
$this->form_validation->set_rules('phone_number', 'Phone', 'trim|required|xss_clean');
$this->form_validation->set_rules('date_of_birth', 'Date of Birth', 'trim|required|xss_clean');
$this->form_validation->set_rules('address', 'Address', 'trim|required|xss_clean');
$this->form_validation->set_rules('country', 'Country', 'trim|required|xss_clean');
$this->form_validation->set_rules('active', 'Is Active', 'trim|required|xss_clean');
$id = $this->input->post('id');
$person_id = $this->input->post('person_id');
$first_name = $this->input->post('first_name');
$last_name = $this->input->post('last_name');
$date_of_birth = $this->input->post('date_of_birth');
$phone_number = $this->input->post('phone_number');
$account_number = $this->input->post('account_number');
$address = $this->input->post('address');
$country = $this->input->post('country');
$active = $this->input->post('active');
if($this->form_validation->run()==false){
$this->edit();
}else{
$person = array(
'first_name'=>$first_name,
'last_name'=>$last_name,
'date_of_birth'=>$date_of_birth,
'phone_number'=>$phone_number,
'address'=>$address,
'country'=>$country,
);
$account = array(
'is_active'=>$active
);
print_r($account_number);
}
}
View
<script>
$(document).ready(function(){
var max_fields = 5;
var wrapper = $("#new_account_number_container");
var addInput = $("#addInput");
var i;
$(addInput).click(function(e){
i = $("#new_account_number_container input").length;
e.preventDefault();
if(i<max_fields){
i++;
$(wrapper).append('<div><input type="text" name="account_number[]" class="form-control" placeholder="Account Number" required autofocus>Remove<div>');
}
});
$(wrapper).on("click",".remove", function(e){ //user click on remove text
e.preventDefault(); $(this).parent('div').remove();
i--;
});
});
</script>
<div id="new_account_number_container" class="form-group col-sm-8">
<input type="text" name="account_number[]" class="form-control" placeholder="Account Number" autofocus>
<br>
</div>
<div class="form-group col-sm-8">
<button class="pull-right btn btn-primary" id="addInput">Add</button>
</div>
First thing, I can not see <form> in your code. Without this tag, you can not get desired behaviour:
After that,
To give you formatted code snippet I am posting that suggestion as an answer:
// this is the id of the form
$("#form_id").submit(function(e) {
var url = "path/to/your/script.php"; // the script where you handle the form input.
$.ajax({
type: "POST",
url: url,
data: $("#form_id").serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // show response from the php script.
}
});
e.preventDefault(); // avoid to execute the actual submit of the form.
});
We need to remember that, PHP serves as back-end application. So anything dynamic (like DOM input text in your case) may NOT be submitted simply because the <form> tag is not updated that you have new text-box input.
One of the thing you could do is to use ajax for form submitting. Because it is Client-Side Script, it could detect all DOM input text box on your page, and serialized it before send the request to the back-end.
First by adding a <form> tag between your input and button component. Example like <form id="frm" name="frm">.
Second, by adding a button which trigger a JavaScript function.
function update(){
if(confirm("Are you sure?")==true){
$.post(
"*absolute_project_root_path*/*controller*/update",
$('#frm').serialize(),
function(response){
//what to do with your response..
}
);
}
return false;
}
Then you can access the submitted form in the back-end like usual.
Here i am able to clear data but when i push value from other radio button its load again previous data which i don't want.
I want textarea data should be clear permanently on radio button click and should not load with any other.
Here is my code
<div class="portlet-body">
#foreach($students as $student)
<div>
<input type="radio" value="{{$student->id}}" name="student_lists[]" onclick="getdata( {{ $student->id }} )"/>
{{$lists->name}}
<span></span>
</div>
<div id="students-data"></div>
#endforeach
</div>
script
<script>
function getdata(id)
{
$('#textbx').val(null);
$.ajax({
url: '/students/'+id,
type: "POST",
success: function (data) {
$('#students-data').html(data);
}
});
}
Controller method to get HTML
public function loadData($id)
{
$students = DB::table('students')->select('name' , 'id')->where('user_id' , $id)->get();
$data = '';
$data .= '<div class="form-group">
<label class="control-label col-md-1">
</label>
<div class="col-md-8">
<label class="">';
foreach ($students as $student) {
$data .= "<input type='checkbox' class='chkbx' name='custom' onclick='push()' value='{$student->name}'/> {$student->name}
<span></span>";
}
$data .='</label>
</div>
</div>';
return $data;
}
Script to push data in text area
<script>
function push()
{
$checks = $(".chkbx:checkbox");
$checks.on('change', function() {
var data = $checks.filter(":checked").map(function(i,v){
return this.value;
}).get().join("\n");
$('#textbx').val(data);
});
}
</script>
Textarea where i push values
<textarea name="fields" id="textbx" class="form-control" rows="8" ></textarea>
Please help how can i hard reset textarea value.
Remove the push function, keep the change event and delegate it so you can trigger the code on the dynamically added elements, select the checkboxes relative to your clicked checkobx
$(function(){
$('body').on('change',".chkbx:checkbox", function() {
var data = $(this).parent().find(':checkbox:checked').map(function(i,v){
return $(v).val();
}).get().join("\n");
$('#textbx').val(data);
});
});
if you have student->id as a value and want student->name to be apppended to the textarea then you need to alter your html as follows
add a custom attribute called data-name with the student name
$data .= "<input type='checkbox' class='chkbx' name='custom' data-name=' {$student->name}' value='{$student->name}'/> {$student->name}
<span></span>";
and the js map to return:
return $(v).attr('data-id');
At beginning before looping statement initialize your student-data variables to 0 or null.
All the variables you want to display should be initialized to 0 or NULL, so that every time function is called first the values will be set to null then for loop stores its values.
The news feed on the sites dashboard I'm working on has multiple items from different users; and can also be commented on. However, whenever you write a comment under each post, it only posts to the post at the top of the feed (the most recent one). Comments are posted instantly by pressing the enter key, which then runs this JS code which is on the index.php page.
$(function(){
$('#comment_body').live( 'keypress' , function (e) {
var boxVal = $(this).val();
var sendTo = $('#to_id').val();
if ( e.keyCode == '13' ) {
e.preventDefault();
$.post( 'instantcom.php' , { 'comment_body' : boxVal , 'activity_id' : sendTo } , function () {
// reload data or just leave blank
} );
$('#comment_body').val('');
}
} );
});
Then, the HTML for the comment box on each post is as follows:
<p align="center" style="height:45px;">
<input type="text" name="comment_body" id="comment_body" style="margin-top:12px;border:1px solid blue !important;width:329px;height:21px;" />
<span class=" glyphicons-icon camera" style="position:relative;bottom:50px;left:155px;"></span></p>
<input name="type" type="hidden" value="a" />
<input name="activity_id" id="to_id" type="hidden" value="' . $act_item_id . '" />
The ' . $act_item_id . ' is just a PHP variable which contains the unique ID of the status update.
So then, any ideas as to why comments are only posting to the most recent posts instead of the ones they're meant to post to?
You're using an id to identify which post you're commenting against? to_id right? Well, that's an id on the page, id's should be unique to the page.