How to only validate a form when toggled - javascript

I have a form with bootstrap toggles for each day of the week. When toggled "yes", a div with two select boxes appears. When toggled "no", the div disappears. This is functioning perfectly, but I want to use JavaScript to validate the form.
However, if one or more of the days are toggled "no", I don't want to validate that section of the form.
$('#mycheckbox').change(function() {
$('#mycheckboxdiv').toggle("fast");
});
I have tried multiple suggestions from online mostly using :visible, but I still cant get it to work.
I'm still new to JavaScript.
<link href="https://gitcdn.github.io/bootstrap-toggle/2.2.2/css/bootstrap-toggle.min.css" rel="stylesheet">
<script src="https://gitcdn.github.io/bootstrap-toggle/2.2.2/js/bootstrap-toggle.min.js"></script>
<input name="everyday" name="mycheckbox" id="mycheckbox" type="checkbox" data-toggle="toggle" data-on="Yes" data-off="No" data-onstyle="success" data-offstyle="danger" value="0">
<div id="mycheckboxdiv" style="display:none">
<select class="btn btn-default" name="ed_from" id="ed_from" method="post">
<option disabled selected>From</option>
<?php for($i = 1; $i < 25; $i++): ?>
<option value="<?= $i; ?>"><?= $i % 12 ? $i % 12 : 12 ?>:00 <?= $i >= 12 ? 'pm' : 'am' ?></option>
<?php endfor ?>
</select>
<select class="btn btn-default" name="ed_to" method="post">
<option disabled selected>Until</option>
<?php for($i = 1; $i < 25; $i++): ?>
<option value="<?= $i; ?>"><?= $i % 12 ? $i % 12 : 12 ?>:00 <?= $i >= 12 ? 'pm' : 'am' ?></option>
<?php endfor ?>
</select>
<div><label class=" err2 err" id="ed_from_error">Please select your availability</label></div>
<br><br>
</div>
<div class="form-group">
<input type="submit" class="btn btn-primary btn-lg btn-block" id="submit" method="post" value="next">
</div>

There are many errors in the HTML. method="post" attribute not available for select DOM. Use <form method="POST"></form> element to submit your data. Here is the example but I not used the <form> tag.
HTML Code
<input name="everyday" id="mycheckbox" type="checkbox" value="1" >
<div id="mycheckboxdiv" style="display:none">
<select class="btn btn-default" name="ed_from" id="ed_from">
<option disabled selected value="">From</option>
<option value="1">1:00 AM</option>
</select>
<select class="btn btn-default" name="ed_to" id="ed_to">
<option disabled selected value="">Until</option>
<option value="1">1:00 AM</option>
</select>
<div><label class=" err2 err" id="ed_from_error">Please select your availability</label></div>
<br><br>
</div>
<div class="form-group">
<input type="submit" class="btn btn-primary btn-lg btn-block" id="submit" method="post" value="next">
</div>
jQuery Code
$('#mycheckbox').change(function() {
$('#mycheckboxdiv').toggle("fast");
});
$('#submit').click(function() {
if($('#mycheckbox').val()){
if($('#ed_from option:selected').val() == '' || $('#ed_to option:selected').val() == ''){
$('#ed_from_error').show();
}else
$('#ed_from_error').hide();
}
});
https://fiddle.jshell.net/LLayz0k3/
If you want to try with <form> tag
$( "#target" ).submit(function( event ) {
event.preventDefault();
// Add your validation here
....
....
});

You might try to use one of the solutions for checking for visibility from this question.
This is only if you are doing manual validation of some kind. If you are using some library you will need to provide more specifics if you need more help on how to unregister the validation when your submit is pressed.
Edit: More closely match posted snippet.
// unhide if checkbox is checked on page load (probably not needed)
if ($("#mycheckbox")[0].checked) {
$("#mycheckboxdiv").show("fast")
}
// toggle when checkbox changes
$("#mycheckbox").change(function() {
$("#mycheckboxdiv").toggle("fast");
});
// validation
$("#submit").click(function() {
if ($("#mycheckboxdiv").is(":visible")) { // jquery
//if ($("#mycheckboxdiv")[0].offsetParent != null) { // non jquery
// do validation here
if ($("#ed_to").val() == null || $("#ed_from").val() == null) {
$("#ed_from_error_1").show("fast");
return false;
} else {
$("#ed_from_error_1").hide("fast");
}
if ($("#ed_to").val() <= $("#ed_from").val()) {
$("#ed_from_error_2").show("fast");
return false;
} else {
$("#ed_from_error_2").hide("fast");
}
}
// alter just for snippet
alert("All good");
return true;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://gitcdn.github.io/bootstrap-toggle/2.2.2/css/bootstrap-toggle.min.css" rel="stylesheet">
<script src="https://gitcdn.github.io/bootstrap-toggle/2.2.2/js/bootstrap-toggle.min.js"></script>
<input name="everyday" name="mycheckbox" id="mycheckbox" type="checkbox" data-toggle="toggle" data-on="Yes" data-off="No" data-onstyle="success" data-offstyle="danger" value="0">
<div id="mycheckboxdiv" style="display:none">
<select class="btn btn-default" name="ed_from" id="ed_from" method="post">
<option disabled selected>From</option>
<option value="1">01:00</option>
<option value="2">02:00</option>
<option value="3">03:00</option>
<option value="4">04:00</option>
</select>
<select class="btn btn-default" name="ed_to" id="ed_to" method="post">
<option disabled selected>Until</option>
<option value="1">01:00</option>
<option value="2">02:00</option>
<option value="3">03:00</option>
<option value="4">04:00</option>
</select>
<div>
<label class="err2 err" id="ed_from_error_1" style="display:none">Please select your availability</label>
<label class="err2 err" id="ed_from_error_2" style="display:none">Until must be later than from</label>
</div>
<br><br>
</div>
<div class="form-group">
<input type="submit" class="btn btn-primary btn-lg btn-block" id="submit" method="post" value="next">
</div>

Ok after plenty of research I've figured out what I was missing. A lot of the different JavaScript I was trying out was actually perfectly valid and would have worked fine however I discovered the underlying issue was actually with not initializing the bootstrap toggle before running any other JavaScript.
$('#mycheckbox').bootstrapToggle('off');
http://www.bootstraptoggle.com/
I now have a code that displays the selects and validates them when toggle is on, or hides and does not validate them when the toggle is off.
//initialize bootstrap.
$('#mycheckbox').bootstrapToggle('off');
//Show/Hide div when toggled.
$('#mycheckbox').change(function() {
$('#mycheckboxdiv').toggle("fast");
});
$(function availability(){
$('.err').hide();
$("#submit").click(function() {
//If toggle is checked:
if ($('#mycheckbox').prop("checked")){
//validate.
var ed_from = $("#ed_from").val();
if (ed_from == null) {
$("label#ed_from_error").show();
$("#ed_from").focus();
document.getElementById('ed_from').style.borderColor = "red";
return false;
}else{
if (ed_from != null) {
document.getElementById('ed_from').style.borderColor = "green";
}
}
}
});
});

Related

Select show hide div after specific values input

I'm basically trying to
Show upload div when status input valued="Tidak aktif"
Hide upload div when status input valued ="Aktif"
This is my code
<h2>EDIT STATUS PEGAWAI</h2>
<?php
$ambildata = $koneksi -> query ("SELECT * FROM diniyah WHERE ID ='$_GET[id]'");
$pecahdata = $ambildata -> fetch_assoc();
echo "<pre>" ;
print_r($pecahdata);
echo "</pre>";
?>
<h2>GANTI STATUS PEGAWAI : </h2>
<form method="post" enctype="multipart/form-data">
<select class="form-control form-control-lg" name="STATUS" id="STATUS">
<option value="Aktif">AKTIF</option>
<option value="Tidak Aktif">TIDAK AKTIF</option>
<div class="form-group" style="display:none;">
<input type="file" name="uploaddiniyah" class="form-control">
<button class="btn btn-primary" name="ubah">Konfirmasi</button>
</div>
</form>
<?php
if (isset($_POST['Tidak Aktif'])){
include'upload.php';
}else{
include'home.php';
}
?>
<?php
if (isset($_POST['ubah'])) {
$uploaddiniyah = true;
$namafoto = $_FILES ['uploaddiniyah']['name'];
$lokasifoto = $_FILES ['uploaddiniyah']['tmp_name'];
move_uploaded_file($lokasifoto, "../fotodokumen/".$namafoto);
//jk foto dirubah
$koneksi->query("UPDATE diniyah SET status='$_POST[STATUS]' WHERE ID='$_GET[id]'");
$update_gambar=mysqli_query($koneksi,"UPDATE diniyah SET uploaddiniyah='$namafoto' WHERE ID='$_GET[id]'");
echo "<div class='alert alert-info'> Data Tersimpan</div>";
}
?>
Is there a mistake on my code?
You can use basic js for do that like:
let status = document.getElementById('STATUS');
let upload = document.getElementById('upload');
status.onchange = function()
{
if(this.value === "Tidak Aktif"){
upload.style.display = 'block';
}else{
upload.style.display = 'none';
}
}
<select class="form-control form-control-lg" name="STATUS" id="STATUS">
<option value="Aktif">AKTIF</option>
<option value="Tidak Aktif">TIDAK AKTIF</option>
</select>
<div class="form-group" id='upload' style="display:none;">
<input type="file" name="uploaddiniyah" class="form-control">
</div>

jquery working in chrome, mozilla and IE but not in safari

I have the following HTML code in my page.
<div class="form-device">
<label class="control-label col-lg-2">Bridges </label>
<div class="col-md-4" style="font-size: 16px;">
<div class="input-icon right">
<div class="col-md-3" style="padding-left: 0;">
<lable><input type="radio" name="bridge" value="default" <?if (!empty($device_info['bridge']) && $device_info['bridge']=='default') {echo "checked";}?>> Default</lable>
</div>
<div class="col-md-3" style="padding-left: 0;">
<lable><input type="radio" name="bridge" value="2" <?if (!empty($device_info['bridge']) && $device_info['bridge']=='2') {echo "checked";}?>> 2</lable>
</div>
<div class="col-md-3" style="padding-left: 0;">
<lable><input type="radio" name="bridge" value="3" <?if (!empty($device_info['bridge']) && $device_info['bridge']=='3') {echo "checked";}?>> 3</lable>
</div>
<div class="col-md-3" style="padding-left: 0;">
<lable><input type="radio" name="bridge" value="4" <?if (!empty($device_info['bridge']) && $device_info['bridge']=='4') {echo "checked";}?>> 4</lable>
</div>
</div>
</div>
</div>
<div class="clearfix"><br></div>
<div class="clearfix"><br></div>
<div class="form-device">
<label class="control-label col-lg-2">Select Group</label>
<div class="col-md-4">
<div class="input-icon right">
<select name="fk_group_id" class="select-basic form-control" id="fk_group_id" required="required">
<option value="" data-target="always">Select Group</option>
<?
foreach ($group_list as $group_list_key => $group_list_value) {
if ($group_list_value['group_id']==$device_info['fk_group_id']) {
$selected='selected="selected"';
}
else{
$selected='';
}
?>
<option value="<?=$group_list_value['group_id'];?>" data-target="<?=$group_list_value['bridge'];?>" <?=$selected;?> ><?=$group_list_value['group_name'];?></option>
<?
}
?>
</select>
</div>
</div>
</div>
and have following Jquery code in my page for dynamically changing dropdown value change.
$('input[type=radio][name=bridge]').change(function() {
var val = $('input[type=radio][name=bridge]:checked').val();
$('#fk_group_id>option[value]').hide();
$('#fk_group_id>option[data-target=always]').show();
$('#fk_group_id>option[data-target='+ val +']').show();
$('#fk_group_id>option:eq(0)').prop('selected', true);
});
I want different "Select Group" dropdown for changing Bridges value. all the things working fine in chrome, Mozilla and IE but in safari "Select Group" value not changing after changing "Bridges" value. can you give me any suggestion for what is not working in safari in above code? or what are the other way to achieve this? any help will be appreciated.
Try wrapping your code in the document ready function like this. Which will eventually bind the events to bridge all input[type=radio][name=bridge] once DOM is ready.
$(document).ready(function(){
$('input[type=radio][name=bridge]').change(function() {
var val = $('input[type=radio][name=bridge]:checked').val();
$('#fk_group_id>option[value]').hide();
$('#fk_group_id>option[data-target=always]').show();
$('#fk_group_id>option[data-target='+ val +']').show();
$('#fk_group_id>option:eq(0)').prop('selected', true);
});
});
If you are creating dynamic elements use below code that will find for the input[type=radio][name=bridge] on DOM.
$(document).on("change", "input[type=radio][name=bridge]", (function() {
var val = $('input[type=radio][name=bridge]:checked').val();
$('#fk_group_id>option[value]').hide();
$('#fk_group_id>option[data-target=always]').show();
$('#fk_group_id>option[data-target='+ val +']').show();
$('#fk_group_id>option:eq(0)').prop('selected', true);
});
your issue is in html tags
<label> is right tag not <lable>
put checked =
<lable>
<input type="radio" name="bridge" value="2" <?if
(!empty($device_info['bridge'])
&& $device_info['bridge']=='2') {echo
"checked";}?>> 2</lable>
change it to
<label>
<input type="radio" name="bridge"
value="default" checked = "<?if (!empty($device_info['bridge'])
&& $device_info['bridge']=='default') {echo 'checked';}?>" >
Default
</label>
what are those server side tags
I find Instead of $('elem').show() and $('elem').hide() try using...
$('elem').attr( 'data-display', 'block');
$('elem').attr( 'data-display', 'none');
In CSS add...
Attribute selector used twice to increase specificity ;)
[data-display][data-display='none'] {
display:none!important;
}
[data-display][data-display='block'] {
display:block!important;
}

Select Option Doesn't Set on Button Click with jQuery

I've tried following a couple of answers with no success. I am trying to get the select box to go back to the "Please Select One Option" when the Add Exercise button is clicked. I got it to work in a simple scenario like this:
<div id="retro_add_exercises">
<div class="row">
<div class="input-field col s12">
<div class="select-wrapper initialized">
<select class="initialized" id="exercise_category">
<option value="0" disabled="" selected="">Please Select One</option>
<option value="1">Cardio</option>
<option value="2">Weight Lifting</option>
<option value="3">Stretching</option>
</select>
</div>
</div>
</div>
<!-- CARDIO SELECT FIELD -->
<div class="row" id="select_cardio">
<form method="POST" id="cardio_form">
<div class="input-field col s12">
<button class="btn waves-effect waves-light" id="add_exercise_from_cardio" type="submit" name="action" value="ADD">Add Exercise from cardio</button>
</div>
</form>
</div>
<script type="text/javascript">
$(document).ready(function() {
$('#add_exercise_from_cardio').click(function() {
$('#exercise_category').val('0').change();
});
});
</script>
But in my main project, it isn't working when I have the row show and hide on button click too. Any help would be appreciated.
$(document).ready(function() {
$('#retroactive_date_form').submit(function(e) {
e.preventDefault();
var date = $('#retroactive_date_picker');
var exercise_date = date.val();
if (exercise_date !== '') {
var exercise_category;
var weight_set_type;
console.log(exercise_date);
date.prop('disabled', true);
$('#retroactive_date_submit').addClass('disabled');
$('#retro_add_exercises').show();
//Exercise Category Function
$('#exercise_category').on('change', function() {
exercise_category = $('#exercise_category').val();
console.log(exercise_category);
if (this.value === '1')
{
$('#select_cardio').show();
$('#drop_or_reg_set_select_exercise').hide();
$('#super_set_select_exercises').hide();
$('#drop_and_regular_set_action_btn').hide();
$('#super_set_action_btn').hide();
$('#super_set_table_row').hide();
$('#drop_or_reg_set_table_row').hide();
}
else
$('#select_cardio').hide();
if (this.value === '2')
{
$('#select_weight').show()
}
else
$('#select_weight').hide();
if (this.value === '3')
{
$('#select_stretch_fields').show();
$('#select_cardio').hide();
$('#drop_or_reg_set_select_exercise').hide();
$('#super_set_select_exercises').hide();
$('#drop_and_regular_set_action_btn').hide();
$('#super_set_action_btn').hide();
$('#super_set_table_row').hide();
$('#select_weight').hide();
$('#drop_or_reg_set_table_row').hide();
}
else
$('#select_stretch_fields').hide();
return exercise_category;
});
///////////Cardio Training Functions///////////////
//Selecting Cardio Exercise
$('#cardio_exercise').on('change', function (e) {
var cardio_exercise;
cardio_exercise = $('#cardio_exercise').val();
console.log(cardio_exercise);
});
//Adding Another Exercise After Done Adding Current Cardio Exercise
$('#add_exercise_from_cardio').on('click', function(e) {
e.preventDefault();
$('#exercise_category option[value="0"]').attr('selected', true);
$('#select_cardio').hide();
$('#drop_or_reg_set_select_exercise').hide();
$('#super_set_select_exercises').hide();
$('#drop_and_regular_set_action_btn').hide();
$('#super_set_action_btn').hide();
$('#super_set_table_row').hide();
$('#drop_or_reg_set_table_row').hide();
});
//Error Handling If No Date is Selected Before Starting
else {
alert('Please select date')
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="retro_add_exercises" style="display:none">
<div class="row">
<div class="input-field col s12">
<div class="select-wrapper initialized"><span class="caret">▼</span>
<select class="initialized" id="exercise_category">
<option value="0" disabled="" selected="">Please Select One</option>
<option value="1">Cardio</option>
<option value="2">Weight Lifting</option>
<option value="3">Stretching</option>
</select>
</div>
<label>Choose Exercise Type</label>
</div>
</div>
<!-- CARDIO SELECT FIELD -->
<div class="row" style="display:none" id="select_cardio">
<form method="POST" id="cardio_form">
<div class="input-field col s12">
<div class="select-wrapper initialized"><span class="caret">▼</span>
<select id="cardio_exercise" name="cardio_exercise" class="initialized">
<option value="0" disabled selected>Choose Cardio Exercise</option>
<option value="1">Jumping Jacks</option>
<option value="2">Jump Rope</option>
<option value="3">Precor</option>
<option value="4">Running (outside)</option>
<option value="5">Swimming</option>
<option value="6">Treadmill</option>
</select>
</div>
<input type="date" style="display:none" id="cardio_exercise_date" name="cardio_exercise_date">
<input placeholder="Duration (minutes)" name="cardio_duration" id="cardio_duration" type="number" class="validate">
<input placeholder="Distance (optional)" name="cardio_distance" id="cardio_distance" type="number" class="validate">
<button class="btn waves-effect waves-light" id="add_exercise_from_cardio" type="submit" name="action" value="ADD">Add Exercise</button>
<button class="btn waves-effect waves-light" id="finish_tracking" type="submit" name="action" value="FINISH">Finish Workout</button>
<label for="cardio_exercise">Choose Exercise</label>
</div>
</form>
</div>
The jQuery documentation dictates that since jQuery 1.6, attr will not update the dynamic state of a DOM element. In addition, it appears your select is disabled after being selected. Try:
$('#exercise_category option[value="0"]').prop('disabled', false);
$('#exercise_category option[value="0"]').prop('selected', true);
There is probably a better and more efficient way to solve it, but I figured it out. I wrapped the select option in form wrappers and gave the form an ID. Then on the button click I triggered reset of the form using
$('#button_id').on('click', function(e) {
e.preventDefault();
$('#form_id').trigger('reset');
});
Although I'm sure there is a better way, this method worked for me and hopefully it works for someone else too.

Validate div is not empty with jquery

I need to validate that both the text input, .search-results div within the "Current Images" fieldset and dropdown selection are all not empty. I have the logic for the text input and dropdown working, but can't figure out why the empty div logic is not working:
<div class="input-group col-md-6">
<input type="text" class="form-control" placeholder="Search by Asset ID" maxlength="64" class="form-control" id="imageid" name="imageid"> <span class="input-group-btn">
<button class="btn btn-default image-search" type="button">Search</button>
</span>
</div>
<fieldset class="scheduler-border">
<legend class="scheduler-border">Current Images</legend>
<div class="scheduler-broder">
<div class="search-results"></div>
</div>
</fieldset>
</div>
<div class="form-group">
<label for="image">Select Asset Type:</label>
<select id='crop' class="btn btn-default" data-toggle="dropdown">
<option value="default">Choose Type</option>
<option value="now">Now</option>
<option value="livefeeds">Live Feeds</option>
</select>
</div>
<div class="form-group">
<label for="imageid">Select an image</label>
<input type="file" name="file" class="btn btn-default form-control" id="file" accept="image/jpg, image/png, image/jpeg" />
</div>
function checkForInputs() {
var filledUp = $("#imageid").val() != '' && $("#crop").val() != "default" && $(".search-results").val() != '';
if (!filledUp) {
$("#file").attr("disabled", true);
} else if (filledUp) {
$("#file").attr("disabled", false);
}
}
$("#imageid").keyup(function () {
checkForInputs();
});
$("#crop").change(function () {
checkForInputs();
});
checkForInputs();
JSfiddle: link
Use $(".search-results").text() instead of $(".search-results").val()
Do the same for all the elements that don't belong to a form, like div, span, p, etc.
Take a look at the doc: http://api.jquery.com/val/
Method .val() as it described on jquery website:
Get the current value of the first element in the set of matched elements or set the value of every matched element.
You should use .text() instead of .val()
In this case your validation should be
var filledUp = $("#imageid").val() != '' && $("#crop").val() != "default" && $(".search-results").text() != '';
So this jsfiddle is working
you can use
if($('#mydiv').html().length() == 0)
{
//do something
}
this is for compare with empty value
other way to do this task is compare with function "children", example.
if($('.search-results').children.length == 0)
{
// dosomething
}
good luck !

Ask a question using jquery after submitting a form but before processing it

Please see my answer to this question below. It is based upon Kevin's input, another question on stack overflow plus some trial and error.
I am trying to do something I think is fairly simple, yet I keep failing. I have a form on my page, the user has the option to check a box that will post their input to their facebook wall using the javascript SDK. I am having trouble getting the form to post normally after the user have confirmed or canceled posting to their facebook wall. Specifically, it either doesn't wait for an answer if I simply have "return true" at the end of the function or if I add return false to the end, but insert return true into my callback function for the facebook api call, it waits for me to answer and submits to the facebook wall as expected but then does nothing.
Here is my code so far (this is the second example, posts to facebook fine but then does not submit form normally):
<script type="text/javascript">
$(function() {
$('#search').submit(function() {
var type = $('#type').val();
if((type == 'o' || type == 'r') && $('#fb-publish').attr('checked') == true) {
var start = $('#start :selected').text();
var dest = $('#dest :selected').text();
var date = $('#datepicker').val();
var time = $('#time').val();
var seats = $('#spots').val();
var notes = $('#notes').val();
console.log('type: ',type);
if(type == "r") {
var begin = "I need a ride";
if(seats > 1) {
var end = " for "+seats+" people.";
}
else {
var end = '.';
}
}
else {
var begin = "I'm offering a ride";
if(seats > 1) {
var end = " for "+seats+" people.";
}
else {
var end = ' for 1 person.';
}
}
publishWallPost('{{ page.slug }}', notes, begin + " from " +start+" to " + dest + " on "+date+" at " + time + end);
return false;
}
else {
alert('you are browsing!');
return true;
}
});
});
</script>
<script>
<!--
function publishWallPost(slug, message, description) {
var attachment = {'name':'Backcountryride.com','description':description,'media':[{'type':'image','src':'http://dev.backcountryride.com/images/vanlogo.jpg','href':'http://backcountryride.com/' + slug + '/'}]};
FB.ui({
method: 'stream.publish',
message: message,
attachment: attachment,
user_message_prompt: 'post this ride to your wall?'
},
function(response) {
if (response && response.post_id) {
alert('Ride was published to your Facebook wall.');
return true;
} else {
alert('Ride was not published to your Facebook wall.');
return true;
}
});
}
//-->
</script>
And here is my form, if that is of any help:
<form action="quick_process.php" method="post" name="search" id="search" >
<label for="type" id="quick_label1" >Choose Action</label>
<select name="type" size="1" id="type">
<option value="">Please Select</option>
<option value="o" <?php if(isset($type) && $type == 'o') echo ' selected="selected" '; ?> id="option1">Offer a Ride</option>
<option value="r" <?php if(isset($type) && $type == 'r') echo ' selected="selected" '; ?> id="option2">Request a Ride</option>
<option value="b" <?php if(isset($type) && $type == 'b') echo ' selected="selected" '; ?> id="option3">Browse All</option>
</select><br />
<div>
<label for="date" >Date</label>
<input type="text" name="date" id="datepicker" value="<?php if(isset($date)) echo $date; ?>" /><br />
<label for="time">Time</label>
<input type="text" id="time" name="time" value="<?php if(isset($time)) echo $time; ?>" /><br/>
<label for="start_id">From</label>
<select name="start_id" size="1" id="start">
<?php
echo selectNode($start_id);
?>
</select><br />
<label for="dest_id">To</label>
<select name="dest_id" size="1" id="dest">
<?php
echo selectNode($dest_id);
?>
</select><br />
<label for="spots" id="quick_label2">Seats or People</label>
<select id="spots" name="spots">
<option value="" >0</option>
<?php
for($i=1;$i<=9;$i++) {
echo '<option value="'.$i.'"';
if(isset($spots) && $i == $spots) echo ' selected="selected" ';
echo '">'.$i.'</option>';
}
?>
</select><br />
<div id="offer-notes">
<label>Notes / Comments</label>
<textarea name="offer_notes" id="notes" ><?php if(isset($offer_notes)) echo $offer_notes; ?></textarea>
</div>
<label>Send To</label>
<select name="distribution" size="1" >
<option value="" >Please Select</option>
<option value="1">Everyone</option>
<option value="2">Friends Only</option>
<option value="3">Friends of Friends</option>
</select>
<label>Post to your Facebook Wall</label>
<input type="checkbox" name="fB_publish" value="Y" id="fb-publish"/>
<input type="hidden" value="add" name="action" />
<input type="hidden" value="<?php echo $_SESSION['user_id']; ?>" name="user_id" />
<input type="hidden" value="process" name="process_quick" />
<input type="submit" value="Submit" name="submit" class="form-submit" />
</div>
</form>
Thanks in advance for any help!
I think I know what your problem is. When you run the submit function on a form, it wants to submit right away, however, if you return false on it, the form won't submit. What you want is to write a different function that will handle your fb post....then at the end of that logic, you'd want to do a $('#search').submit();
So for example....
$('#submitButton').click(function(e){
e.preventDefault();
[All your logic here in your original function]
publishWallPost('{{ page.slug }}', notes, begin + " from " +start+" to " + dest + " on "+date+" at " + time + end);
$('#search').submit();
});
You will want to rewrite your form submit button as so...since you don't want it to first the submit function of the form, you want it to run your new function first.
<input type="button" id="submitButton" value="Submit" name="submitme" class="form-submit" />
So what you're doing here is....you want to run your logic on the form, then you want to do your facebook posting, or not....then you'd run the actual submit of the form to your php post once you've called your FB post.
I hope that makes sense.
In case anyone else is trying to do this in the future, here is what the final code looked like. Thank you kevin.mansel for pointing me in the right direction. I needed to add the submit() to the callback function and the submit button for the form needed to be OUTSIDE the form tags or else it breaks the javascript. Here is the javascript:
$(function() {
$('#submitButton').click(function(e) {
e.preventDefault();
var type = $('#type').val();
if((type == 'o' || type == 'r') && $('#fb-publish').attr('checked') == true) {
[logic from original post]
publishWallPost('{{ page.slug }}', notes, description);
}
else $('#search').submit();
});
});
</script>
<script>
<!--
function publishWallPost(slug, message, description) {
var attachment = {'name':'Backcountryride.com','description':description,'media':[{'type':'image','src':'http://dev.backcountryride.com/images/vanlogo.jpg','href':'http://backcountryride.com/' + slug + '/'}]};
FB.ui({
method: 'stream.publish',
message: message,
attachment: attachment,
user_message_prompt: 'post this ride to your wall?'
},
function(response) {
if (response && response.post_id) {
alert('Ride was published to your Facebook wall.');
$('#search').submit();
} else {
alert('Ride was not published to your Facebook wall.');
$('#search').submit();
}
});
}
//-->
</script>
Here is the HTML form:
<form action="quick_process.php" method="post" name="search" id="search" >
[form inputs]
</form>
<input type="submit" value="Submit" name="submit" class="form-submit" id="submitButton" />
Note that the submit button is outside the form tags (or it could be a link or image or whatever with a click event bound to it.)

Categories

Resources