For some reason a certain div will now show up when i click a button. I'm fairly new to JS so can't really figure out why is it only on that one. Basically the order should be
Click on Add Shots -> Show Games and Rounds ( Works Fine) -> Click Submit -> Show Targets on each round (Works Fine) -> Click Target -> Show Fill in form (the "fillshotsdiv") (NOT working).
Below is my code. What am i missing?
JS
<script>
$(function() {
$(".but").on("click",function(e) {
e.preventDefault();
$(".contentfill").hide();
$("#"+this.id+"div").show();
});
});
function refreshTargets() {
var load = $.get('functions.php',{gameShots:"<?php echo $_GET['gameShots']; ?>", roundShots:"<?php echo $_GET['roundShots']; ?>",function:"drawTargets"});
$(".targetinfo").html('Refreshing');
load.error(function() {
console.log("Mlkia kaneis");
$(".targetinfo").html('failed to load');
// do something here if request failed
});
load.success(function( res ) {
console.log( "Success" );
$(".targetinfo").html(res);
});
load.done(function() {
console.log( "Completed" );
});
}
</script>
HTML
<div id="addshotsdiv" class="contentfill">
<form action="">
<select name="gameShots" class="gameShot">
<script>
refreshGameDel();
</script>
</select>
<select name="roundShots" class="roundShot">
<option value="nothing">-----</option>
<option value="Round 1">Round 1</option>
<option value="Round 2">Round 2</option>
</select>
<button type="submit" >Submit</button>
</form>
</div>
<div class="targetinfo">
<script>
refreshTargets();
</script>
</div>
<div id="fillshotsdiv" class="contentfill">
<form method="post" action="addScoreToRound.php?targetNo=<?php echo $_GET['targetNo'];?>&gameNo=<?php echo $_GET['gameNo'];?>&roundName=<?php echo $_GET['roundName']; ?>">
<table border="1">
<tr><th>Shot Number</th><th>Arrow 1</th><th>Arrow 2</th><th>Arrow 3</th></tr>
<tr><td>1</td><td><input type="text" name="arrow_1_1"></td><td><input type="text" name="arrow_1_2"></td><td><input type="text" name="arrow_1_3"></td></tr>
<tr><td>2</td><td><input type="text" name="arrow_2_1"></td><td><input type="text" name="arrow_2_2"></td><td><input type="text" name="arrow_2_3"></td></tr>
<tr><td>3</td><td><input type="text" name="arrow_3_1"></td><td><input type="text" name="arrow_3_2"></td><td><input type="text" name="arrow_3_3"></td></tr>
<tr><td>4</td><td><input type="text" name="arrow_4_1"></td><td><input type="text" name="arrow_4_2"></td><td><input type="text" name="arrow_4_3"></td></tr>
<tr><td>5</td><td><input type="text" name="arrow_5_1"></td><td><input type="text" name="arrow_5_2"></td><td><input type="text" name="arrow_5_3"></td></tr>
<tr><td>6</td><td><input type="text" name="arrow_6_1"></td><td><input type="text" name="arrow_6_2"></td><td><input type="text" name="arrow_6_3"></td></tr>
<tr><td>7</td><td><input type="text" name="arrow_7_1"></td><td><input type="text" name="arrow_7_2"></td><td><input type="text" name="arrow_7_3"></td></tr>
<tr><td>8</td><td><input type="text" name="arrow_8_1"></td><td><input type="text" name="arrow_8_2"></td><td><input type="text" name="arrow_8_3"></td></tr>
<tr><td>9</td><td><input type="text" name="arrow_9_1"></td><td><input type="text" name="arrow_9_2"></td><td><input type="text" name="arrow_9_3"></td></tr>
<tr><td>10</td><td><input type="text" name="arrow_10_1"></td><td><input type="text" name="arrow_10_2"></td><td><input type="text" name="arrow_10_3"></td></tr>
</table>
<button type="submit">Submit</button>
</form>
</div>
PHP that refreshTargets calls is
if($_GET['function']=="drawTargets")
{
$gameNo = $_GET['gameShots'];
$roundName = $_GET['roundShots'];
$sql=mysql_query("SELECT * FROM tbl_Round WHERE match_id='$gameNo' && round_name='$roundName'")
or die(mysql_error());
while ($row = mysql_fetch_array($sql)) {
echo '<p><button class="but" id="fillshots" type="button">'.$row["target_name"].'- Player'.$row['player_id'].'</button></p>';
}
}
You need to use event delegation on your click handler because .but is a dynamically inserted element:
$('.targetinfo').on('click', '.but', function(e) {
e.preventDefault();
$('.contentfill').hide();
$('#' + this.id + 'div').show();
});
Related
I have this submit button on my form with a jQuery action to open a window depending on the users choice. However, I just want the window to open if the fields are filled. I have this code and I want to merge it with an if.
$(function() {
$('#chkveg').multiselect({
includeSelectAllOption: true
});
$('#btnget').click(function() {
window.open($('#chkveg').val());
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="http://formmail.kinghost.net/formmail.cgi" method="POST">
<input name="nome" type="text" class="nome" id="nome" required width="100%" placeholder="Nome:">
<input name="cpf" type="text" class="cpf" id="cpf" placeholder="CPF:">
<div style="clear:both"></div><br/>
<input name="nascimento" type="text" class="nascimento" id="nascimento" placeholder="Data de nascimento:">
<select id="chkveg">
<option value="https://pag.ae/7ULKPL7TH">Associados Ancord + C.Dados = R$700,00</option>
<option value="https://pag.ae/7ULKQ8Zm2">Associados Ancord = R$800,00</option>
<option value="https://pag.ae/7ULKQLB9m">Associados Entidades Apoiadoras + C.Dados = R$800,00</option>
</select>
<input id="btnget" class="submit-btn" type="submit" value="INSCREVER-SE">
</form>
For exemple:
IF (#FORM).REQUIRED = TRUE {
(#BUTTON).WINDOWOPEN
}
Thanks
Because you using a submit button you will need to return false, in case if you don't want to do anything. Before that, you need also to check if your required field are empty or not. (i.e. $(your field).val() === "" then it's empty, if all you need have, then call the window.open() function.
Note: you can merge multiple fields for checking ie: $(".your_field1, .your_field2, .your_field3").val() === "" however this is an OR operation.
One possible solution:
$(function() {
$('#btnget').click(function() {
let isEmpty = false;
$('#data_form input,textarea,select').filter(':visible').each(function(i) {
if ($(this).val() === "") {
isEmpty = true;
return false;
}
});
if (isEmpty) {
return false;
}
window.open($('#chkveg').val());
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="data_form" action="http://formmail.kinghost.net/formmail.cgi" method="POST">
<input name="nome" type="text" class="nome" id="nome" required width="100%" placeholder="Nome:">
<input name="cpf" type="text" class="cpf" id="cpf" placeholder="CPF:">
<div style="clear:both"></div><br/>
<input name="nascimento" type="text" class="nascimento" id="nascimento" placeholder="Data de nascimento:">
<select id="chkveg">
<option value="https://pag.ae/7ULKPL7TH">Associados Ancord + C.Dados = R$700,00</option>
<option value="https://pag.ae/7ULKQ8Zm2">Associados Ancord = R$800,00</option>
<option value="https://pag.ae/7ULKQLB9m">Associados Entidades Apoiadoras + C.Dados = R$800,00</option>
</select>
<input id="btnget" class="submit-btn" type="submit" value="INSCREVER-SE">
</form>
If you want only for the required fields, than use filter('[required]:visible') instead of filter(':visible').
I have already gone through questions available on this topic and have tried everything, but still my keyup function is not working.
$(document).ready(function() {
$(document).on('keyup', '.pollOption', function() {
var empty = false;
$(".pollOption").each(function() {
if ($(this).val() == '') {
empty = true;
}
});
if (empty) {
$("#cpsubmit").attr('disabled', 'disabled');
$("#moreop").attr('disabled', 'disabled');
} else {
$("#cpsubmit").removeAttr('disabled');
$("#moreop").removeAttr('disabled');
}
});
//Keep Track of no. of options on the page
var noOfOptions = 2;
// Function to add input fields (since I may have to delete them I've use bootstrap's input-groups, I guess this is causing issue)
$("#moreop").on('click', function() {
noOfOptions++;
$("#options").append("<div class='input-group pollOption'><input class='form-control' type='text' placeholder='New Option' name='op" + noOfOptions + "'/><span class='input-group-addon'><a href='#' id='removeOption' class='text-danger'>Remove</a></span></div>");
});
// To delete any option (only the dynamically created options can be deleted)
$("#cpform").on('click', '#removeOption', function() {
$(this).parents('.input-group').remove();
noOfOptions--;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="cpform" method="POST" action="/polls/add">
<div class="form-group">
<label>Title</label>
<input id="title" type="text" placeholder="Ask your question here..." name="title" class="form-control" />
</div>
<div id="options" class="form-group">
<label>Options</label>
<input type="text" placeholder="Option 1" name="op1" class="form-control pollOption" />
<input type="text" placeholder="Option 2" name="op2" class="form-control pollOption" />
</div>
<button id="moreop" type="button" disabled="disabled" class="btn btn-outline-info btn-primary">More Options</button><br/><br/>
<button id="cpsubmit" type="submit" disabled="disabled" class="btn btn-info btn-primary">Submit</button>
</form>
This code works perfectly for the two inputs already in the HTML part.
When I click on the "More Option" button the new field gets added but the "keyup" does not work on it. In fact, when I enter something on the new added inputs then my "More Option" & "Submit" button gets disabled (really do't know why this is happening).
You've to add the class pollOption to the input and not the div in your append :
$("#options").append("<div class='input-group'><input class='pollOption form-control' ...
_____________________________________________________________^^^^^^^^^^
Instead of :
$("#options").append("<div class='input-group pollOption'><input class='form-control' ...
______________________________________________^^^^^^^^^^
Demo:
$(document).ready(function() {
$(document).on('keyup', '.pollOption', function() {
var empty = false;
$(".pollOption").each(function() {
if ($(this).val() == '') {
empty = true;
}
});
if (empty) {
$("#cpsubmit").attr('disabled', 'disabled');
$("#moreop").attr('disabled', 'disabled');
} else {
$("#cpsubmit").removeAttr('disabled');
$("#moreop").removeAttr('disabled');
}
});
//Keep Track of no. of options on the page
var noOfOptions = 2;
// Function to add input fields (since I may have to delete them I've use bootstrap's input-groups, I guess this is causing issue)
$("#moreop").on('click', function() {
noOfOptions++;
$("#options").append("<div class='input-group'><input class='pollOption form-control' type='text' placeholder='New Option' name='op" + noOfOptions + "'/><span class='input-group-addon'><a href='#' id='removeOption' class='text-danger'>Remove</a></span></div>");
$(this).attr('disabled','disaled');
});
// To delete any option (only the dynamically created options can be deleted)
$("#cpform").on('click', '#removeOption', function() {
$(this).parents('.input-group').remove();
noOfOptions--;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="cpform" method="POST" action="/polls/add">
<div class="form-group">
<label>Title</label>
<input id="title" type="text" placeholder="Ask your question here..." name="title" class="form-control" />
</div>
<div id="options" class="form-group">
<label>Options</label>
<input type="text" placeholder="Option 1" name="op1" class="form-control pollOption" />
<input type="text" placeholder="Option 2" name="op2" class="form-control pollOption" />
</div>
<button id="moreop" type="button" disabled="disabled" class="btn btn-outline-info btn-primary">More Options</button><br/><br/>
<button id="cpsubmit" type="submit" disabled="disabled" class="btn btn-info btn-primary">Submit</button>
</form>
Hi I am creating a website that has a form to search rooms. I wanted to make it so a checkbox, when clicked, show new options AND change the action ="" attribute of the form.
<form class="form-horizontal" action="reservation?action=listRooms" method="POST">
<label for="">Date </label>
<div class="datepicker ll-skin-nigran hasDatepicker">
<input class="form-control" type="text" placeholder="14/03/2016" name="dateReservation" id="date" required="required"/>
</div>
<br />
<div>
<input type="checkbox" name="choice-for" id="choice-form">
<label for="choice-for">Show More Options.</label>
<div class="reveal-if-active">
<label for="">Slots</label>
<select name="slot" name ="slot" id="slot" >
<option value="">Choose a slot </option>
<option value="8h-9h30">8h00-9h30</option>
<option value="9h30-11h">9h30-11h00</option>
<option value="11h-12h30h">11h00-12h30h</option>
<option value="12h30-14h">12h30-14h00</option>
<option value="14h-15h30">14h00-15h30</option>
<option value="15h30-17h">15h30-17h00</option>
<option value="17h-18h30">17h00-18h30</option>
</select>
<br />
<label for="">Display Screens</label>
<input class="form-control" type="text" placeholder=" 26 pouces" name="screen" id="screen" />
<br />
<label for="">CPU</label>
<input class="form-control" type="text" placeholder="Intel Core i5 " name="processor" id="processor" />
<br />
<label for="">RAM</label>
<input class="form-control" type="text" placeholder=" 2Go de RAM ?" name="ram" id="ram" />
<br />
<input type="submit" value="Réserver" class="btn btn-primary" />
</div>
I tried then to use a javascript(JQuery) script to satisfy my expectations:
<script>
$(function() {
$( "#date" ).datepicker({ dateFormat: 'dd/mm/yy' });
});
$("#choice-form").change(function() {
//there i need to know when the checkbox is changed dynamically so the attribute can change too.
$("#form-horizontal).attr("reservation?action=listRooms");
});
var FormStuff = {
init: function() {
this.applyConditionalRequired();
this.bindUIActions();
},
bindUIActions: function() {
$("input[type='radio'], input[type='checkbox']").on("change", this.applyConditionalRequired);
},
applyConditionalRequired: function() {
$(".require-if-active").each(function() {
var el = $(this);
if ($(el.data("require-pair")).is(":checked")) {
el.prop("required", true);
} else {
el.prop("required", false);
}
});
}
};
FormStuff.init();
</script>
Try this:
$("#choice-form").change(function() {
// If checkbox checked
if ( $('#choice-form').is(':checked') ) {
// Set new form action
$('#form-horizontal').attr('action', 'reservation?action=listRooms');
// Reveal additional options
$('.reveal-if-active').show(); // or call .css() with appropriate options
}
});
Ok, let's say you want to add the id(you can use name as well) and value to the action parameter from the form...
$(document).on('click','.checkboxClass',function(){
var id = $(this).attr('id');
var val = $(this).val();
var selectedVal = '&'+id+'='+val;
var methodUrl = $('form.form-horizontal').attr('action');
if($(this).is(':checked')){
methodUrl+= selectedVal;
}
else{
methodUrl = methodUrl.replace(selectedVal,'');
}
$('form.form-horizontal').attr({'action':methodUrl});
});
Now let's say you have a checkbox with the id="myId" and value="myValue", if you check it, the action parameter will become action="reservation?action=listRooms&myId=myValue"
Is this what you asked for?
When I submit this form though Ajax, Ajax posts it multiple times, sometimes posting it up to 10 times, even though the submit button is only clicked once. I don't understand why it is doing this. Any help would be great!
Here is my code:
<script type="text/javascript">
var messageDelay = 2000;
$( init );
function init() {
$('#messageform').show().submit( submitForm );
$('#rtypeshow').hide();
$('a[href="#messageform"]').click( function() {
$('#content').fadeTo( 'slow', .2 );
$('#messageform').fadeIn( 'slow', function() {
$('#senderName').focus();
} )
return false;
} );
$(document).ready(function (){
$("#messagetable").load("messagetable.php");
$("#etype").change(function() {
if ($(this).val() != "0") {
$("#rtypeshow").show();
$('#datepicker').attr('required', 'required');
}else{
$("#rtypeshow").hide()
$("#allowed").hide;
$('#datepicker').removeAttr('required');
$('#allowed1').removeAttr('required');
}
});
});
$(document).ready(function (){
$("#rtype").change(function() {
var selection = $(this).val();
if (selection == "1") {
$("#allowed").show();
$('#allowed1').attr('required', 'required');
}else{
$("#allowed").hide();
$('#allowed1').removeAttr('required');
}
});
});
}
function submitForm() {
var messageform = $(this);
if ( !$('#ename').val() || !$('#message').val() ) {
$('#incompleteMessage').fadeIn().delay(messageDelay).fadeOut();
messageform.fadeOut().delay(messageDelay).fadeIn();
} else {
$('#sendingMessage').fadeIn();
messageform.fadeOut();
$.ajax( {
url: messageform.attr( 'action' ) + "?ajax=true",
type: messageform.attr( 'method' ),
data: messageform.serialize(),
success: submitFinished
} );
}
return false;
}
function submitFinished( response ) {
response = $.trim( response );
$('#sendingMessage').fadeOut();
if ( response == "success" ) {
$('#successMessage').fadeIn().delay(messageDelay).fadeOut();
$('#ename').val( "" );
$('#message').val( "" );
$('#datepicker').val( "" );
$('#allowed1').val( "" );
$('#allowed2').val( "" );
$('#allowed3').val( "" );
$('#allowed4').val( "" );
$("#messagetable").load("messagetable.php");
$('#content').delay(messageDelay+500).fadeTo( 'slow', 1 );
$('#messageform').show().submit( submitForm );
} else {
$('#failureMessage').fadeIn().delay(messageDelay).fadeOut();
$('#messageform').delay(messageDelay+500).fadeIn();
}
}
</script>
<form id="messageform" action="message_forward.php" method="post">
<p>
<label for="ename">Event Name</label>
<input name="ename" type="text" id="ename" required="required">
</p>
<p>
<label for="message">Message</label>
<span id="sprytextarea1">
<textarea name="message" id="message" required="required"></textarea>
<span id="countsprytextarea1"> </span><span class="textareaRequiredMsg">A value is required.</span><span class="textareaMaxCharsMsg">Exceeded maximum number of characters.</span></span></p>
<p>
<label for="etype">Response Required</label>
<select name="etype" size="2" id="etype">
<option value="0" selected="selected">No</option>
<option value="1">Yes</option>
</select>
</p>
<div id="rtypeshow" style="display:none;">
Event Resender End Date:
<span id="sprytextfield1">
<input name="datepicker" type="text" id="datepicker" size="10">
MM/DD/YYYY <span class="textfieldInvalidFormatMsg">Invalid format.</span></span><br>
Send Response To: <select name="eforward" id="eforward">
<?php
do {
?>
<option value="<?php echo $row_Recordset1['cphone']?><?php echo $row_Recordset1['provider']?>"><?php echo $row_Recordset1['fullname']?>-SMS Message via Cell Phone</option>
<option value="<?php echo $row_Recordset1['email']?>"><?php echo $row_Recordset1['fullname']?>-Email Message</option>
<?php
} while ($row_Recordset1 = mysql_fetch_assoc($Recordset1));
$rows = mysql_num_rows($Recordset1);
if($rows > 0) {
mysql_data_seek($Recordset1, 0);
$row_Recordset1 = mysql_fetch_assoc($Recordset1);
}
?>
</select><br>
<label for="question">Question for responses</label>
<input type="text" name="question" id="question" maxlength="18"><br>
<label for="rtype">Response Type</label>
<select name="rtype" size="3" id="rtype">
<option value="0" selected="selected">Standard Yes/No Response</option>
<option value="1">Create Responses</option>
<option value="2">Get Users Own Response</option>
</select>
<div id="allowed" style="display:none;">
<h4>Response Options</h4>
<label for="allowed1">Option 1</label>
<input type="text" name="allowed1" id="allowed1" maxlength="12" placeholder="Required">Max Length = 12
<label for="allowed2"><br>
Option 2</label>
<input type="text" name="allowed2" id="allowed2" maxlength="12" placeholder="Optional">Max Length = 12
<br>
<label for="allowed3">Option 3</label>
<input type="text" name="allowed3" id="allowed3" maxlength="12" placeholder="Optional">Max Length = 12
<label for="allowed4"><br>
Option 4</label>
<input type="text" name="allowed4" id="allowed4" maxlength="12" placeholder="Optional">Max Length = 12
</div>
</div>
<input name="submit" type="submit" value="Send Messages">
</form>
Additional Comments:
Sending a message a second time seems to make it even worse then if the page is refreshed before sending another message.
It looks like your code is attaching the submitForm function multiple times to the submit handler.
In your submitFinished function you attach the handler again:
$('#messageform').show().submit( submitForm );
You can check this by refreshing the page then submitting the form. If it only submits once after refresh then multiple times after that you know that is the problem.
I have random fields for entries. I need to autocomplete using java script and php, but when I try it auto commplete only first field.
My code is:
<script type="text/javascript">
$().ready(function() {
$(".name").keyup(function() {
$(".name").autocomplete("get_profile_list.php", {
width: 260,
matchContains: true,
selectFirst: true
});
});
});
</script>
<script type="text/javascript">
function track() {
var count = jQuery('.abc').length;
jQuery('#track1').append('<span id="track1" class="abc"><br><input type="text" name="name[]" id="name-'+count+'" class="name" value="" size="35"/><input type="text" name="qty[]" id="qty-'+count+'" value="" size="1" onchange="return track();" /><input type="text" name="price[]" id="price-'+count+'" value="" size="1"/></span>');
}
$('input').live("keypress", function(e) {
/* ENTER PRESSED*/
if (e.keyCode == 13) {
/* FOCUS ELEMENT */
var inputs = $(this).parents("form").eq(0).find(":input");
var idx = inputs.index(this);
if (idx == inputs.length - 1) {
inputs[0].select()
} else {
inputs[idx + 1].focus(); // handles submit buttons
inputs[idx + 1].select();
}
return false;
}
});
</script>
</head>
<body>
<?php date_default_timezone_set("Asia/Kolkata");?>
<form name="form" method="post">
Party Name : <input type="text" name="customer" size="30" />
Date and Time : <input type="hidden" name="edt" value="<?php echo date("d-m-Y h:i:s", time());?>"/><?php echo date("d-m-Y h:i:s", time());?>
<br><br>
<strong>Products Details</strong>
<div id="main">
<span id="track1" class="abc">
<input type="text" name="name[]" id="name-0" class="name" value="" size="35" /><input type="text" name="qty[]" id="qty-0" value="" size="1" onchange="return track();" /><input type="text" name="price[]" id="price-0" value="" size="1"/>
</span>
<div id="display">
</div>
</div>
<br><br>
Receiver Name<input type="text" name="receiver" /><br>
<input type="submit" name="submit" />
</form>
</body>
</html>
For example please visit http://computerdada.com/slip1.php
In product details first input box is name of product please test it using words
key, lan.
Thanks.
Use .on()
you are adding element with class name dynamically so the elements that are not presernt at DOM ready doesn't get event handler attached to it.
you need Event Delegation to attach the event handler to the parent element present at DOM ready.
$(document).ready(function () {
$('#track1').on('keyup', '.name', function () {
$(this).autocomplete("get_profile_list.php", {
width: 260,
matchContains: true,
selectFirst: true
});
});
});
Updated after OP's comment.
As you are using jQuery v1.3.2
so you have to use .live()
$(document).ready(function () {
$('.name').live('keyup', function () {
$(this).autocomplete("get_profile_list.php", {
width: 260,
matchContains: true,
selectFirst: true
});
});
});