Adding multiple textboxes using plus button and submit through PHP - javascript

I need to add multiple textboxes using a plus button and remove them using a minus button using Javascript.
After user fills up all the fields and clicks the submit button, I need to fetch all value using PHP.
Example:
Initially, there will only be 1 textbox. When user clicks on + button and already filled up the first field, the a second textbox will appear and also a - button used to remove the textbox. When a user clicks submit, the value in the textboxes will be submitted through PHP.
My code:
<?php
if(isset($_POST["userbtnsubmit"])){
}
?>
<form name="frmfeed" id="frmfeed" enctype="multipart/form-data" method="post" onSubmit="return validateFeedbackForm();">
<input type="text" name="country" id="con" class="form-control oditek-form" placeholder="Add Country">
<input type="button" class="btn btn-success" name="plus" id="plus" value="+">
<input type="button" class="btn btn-danger" name="minus" id="minus" value="-">
<button type="submit" class="btnsub" name="userbtnsubmit" id="btnsubmit">Add</button>
</form>

Note: As stated in the question, the user must type text in an input before another can be be shown.
addRemoveAnother('#plus', '#minus', '#con', '#counter', 3);
function addRemoveAnother(plusBtn, minusBtn, target, counter, limit) {
var i, ii = $(counter).val();
for(i = 0; i <= limit; i++) {
if (i != ii) {
$(target+i).hide();
}
}
$(plusBtn).click(function() {
ii = $(counter).val();
if ($(target+ii).val() != '') {
ii++;
if (ii <= limit) {
$(target+ii).show();
$(counter).val(ii);
}
}
});
$(minusBtn).click(function() {
ii = $(counter).val();
if (ii > 1) {
$(target+ii).val('');
$(target+ii).hide();
ii--;
$(counter).val(ii);
}
});
}
https://jsfiddle.net/curtisweeks/k4kanw6L/

You can combine jQuery PLUS AJAX to achieve the same.
Example :
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
$(document).ready(function(){
$( "#plus" ).on("click", function() {
$( "#frmfeed" ).append( '<input type="text" name="country[]" class="form-control oditek-form" placeholder="Add Country"/>');
});
$("#minus").on("click", function(){
if($("input[name='country[]']").length > 1)
{
$("input[name='country[]']:eq("+(length-1)+")").remove();
}
});
$("#btnsubmit").on("click", function(){
var countries = [];
$("input[name='country[]']").each(function(){
countries.push($(this).prop("value"));
});
console.log(countries);
//AJAX Post Data To Your Server
var postDataObj = {
url: "YOUR_SERVER_FILE",
type: "post",
data: countries,
success: function(data){
//Response Data From Server
}
}
console.log(postDataObj);
$.ajax(postDataObj);
});
});
</script>
</head>
<body>
<form name="frmfeed" id="frmfeed" enctype="multipart/form-data" method="post" onSubmit="return validateFeedbackForm();">
<input type="text" name="country[]" id="con" class="form-control oditek-form" placeholder="Add Country"><br/><br/>
</form>
<input type="button" class="btn btn-success" name="plus" id="plus" value="+"> <input type="button" class="btn btn-danger" name="minus" id="minus" value="-">
<button type="submit" class="btnsub" name="userbtnsubmit" id="btnsubmit">Add</button>
</body>
</html>
JSFiddle Demo

Related

How to apply click event on respective div containing same child and class name

Two div having class name container containing same elements with same class name. Apply Jquery when that respective children are clicked.
HTML CODE
<div class="container">
<input type="button" class="negative" value="-">
<input type="button" class="qty" value="">
<span class="txt">None</span>
<input type="button" class="positive" value="+">
</div>
<div class="container">
<input type="button" class="negative" value="-">
<input type="button" class="qty" value="">
<span class="txt">None</span>
<input type="button" class="positive" value="+">
</div>
I have written Some scripts, which will hide negative input and display None when value is 0, positive input will increase a value
$(document).ready(function() {
var counter = 1;
if ($('.qty').val() === 0 || $('.qty').val() === '') {
$('.qty').hide();
$('.txt').show();
$('.negative').hide();
} else {
$('.txt').hide();
$('.qty').show();
$('.negative').show();
}
$('.positive').click(function() {
$('.negative').show();
$('.qty').show();
$('.txt').hide();
const qty = $('.qty').val();
$('.qty').val(counter);
counter++;
});
$('.negative').click(function() {
const qty = $('.qty').val();
if (qty > 1) {
counter--;
$('.qty').val(counter);
} else {
counter = 1;
$('.negative').hide();
$('.txt').show();
$('.qty').hide();
}
});
});
I am not sure how to use $(this) in above code.
I am beginner in JS and I know this code is not efficient.
If possible make it efficient.
Thank you!!!
I'm doing this in the code below by using .parent().find(). This can be brittle though if you rearrange your layout, so just be careful with it. You'd be better off giving a data attribute to the elements and modifying them that way.
$(document).ready(function() {
$("input").click(function() {
let clickAction = $(this).val();
console.log($(this).val());
let displayElement = $(this).parent().find("input.qty");
let currentval = +$(displayElement).val();
//you could use eval to make this look cleaner, but eval is often frowned upon
if (clickAction == "+") {
currentval++;
} else if (clickAction == "-") {
currentval--
}
$(displayElement).val(currentval);
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
<input type="button" class="negative" value="-">
<input type="button" class="qty" value="0">
<span class="txt">None</span>
<input type="button" class="positive" value="+">
</div>
<div class="container">
<input type="button" class="negative" value="-">
<input type="button" class="qty" value="0">
<span class="txt">None</span>
<input type="button" class="positive" value="+">
</div>

Does The Form Tag Make A Variable Out Of Scope?

I have a variable called checker everything is fine until there is a form tag. After that the variable becomes null? Why? and how do I fix it?
#{
foreach (var f in l)
{
var theDate = f.date;
var timeFrom = f.timeFrom;
var timeUntil = f.timeUntil;
var id = f.id;
<div class="col-lg-offset-1"><b><u> Job Available</u></b><br /></div>
<div><b>#theDate.ToLongDateString()</b></div>
<div class="col-lg-offset-1"><b>#timeFrom.ToShortTimeString() - #timeUntil.ToShortTimeString()</b></div>
<br />
var checker = false;
foreach (var q in Model.Invitations)
{
if (q.CleanerId == Model.Cleaner.id)
{
checker = true;
<div>#checker</div>
}
}
<form action="/Authentication/TakeJob" method="post" role="form">
<input class="invited" data-invited="#checker" type="hidden" name="invited" value="#checker" />
<input type="hidden" name="JobId" value="#id" />
<input type="hidden" name="CleanerId" value="#Model.Cleaner.id" />
<button class="btn btn-success btn-lg acceptButton">I'll Take The Job</button>
</form>
}
}
Try and change the position of the closure, there is no need for your scope to be so wide including the form.
#{
var checker = false;
foreach (var q in Model.Invitations)
{
if (q.CleanerId == Model.Cleaner.id)
{
<div>#checker</div>
//here it works
}
}
}
<form action="/Authentication/TakeJob" method="post" role="form">
//here it is null
<input class="invited" data-invited="#this.checker" type="hidden" name="invited" value="#this.checker" />
<input type="hidden" name="JobId" value="#id" />
<input type="hidden" name="CleanerId" value="#Model.Cleaner.id" />
<button class="btn btn-success btn-lg acceptButton">I'll Take The Job</button>
</form>

Buttons must be pressed in a specific order to send the form - jquery

I am trying to make a puzzle game in which the user must press the button in a specific order in which they fill a textbox (will be hidden) with a password ( 3-digits) if the user pressed the buttons for example ( 3,2,1 ) the form will be submitted automatically and redirecting to another page..
I tried, but I couldn't do it
here are my codes :
<form method="POST">
<input type="text" value="" id="text1" name="text1" style="width: 150px;" />
<br />
<input type="button" value="Click Me" id="1" />
<input type="button" value="Click Me" id="2" />
<input type="button" value="Click Me" id="3" />
</form>
jquery
$(function () {
$('#1').click(function(e) {
var text = $('#text1');
text.val(text.val() + '1');
$('#1').attr("disabled", true);
});
$('#2').click(function(e) {
var text = $('#text1');
text.val(text.val() + '2');
$('#2').attr("disabled", true);
});
$('#3').click(function(e) {
var text = $('#text1');
text.val(text.val() + '3');
$('#3').attr("disabled", true);
});
});
$('#text1').trigger('change') {
alert('Changed');
});
you can do something like this: foreach click on an answer button disabele the current button update the input value..and once the user clicks all answers button check if the combination is correct, if it is the case redirect your page.
$(function () {
var correct_order="321";
var clicks=0;
var max_clicks=$('.answer').length;
$('.answer').click(function(e) {
clicks++;
$('#text1').val($('#text1').val()+$(this).data('info'));
$(this).attr("disabled", true);
if(clicks==max_clicks){
if( $('#text1').val()==correct_order) {
$('#answer_info').html("<p>Correct answer</p>");
window.location.href = "https://yourpage";
}
else {
$('#answer_info').html("<p>Wrong answer</p>");
}
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<form method="POST">
<input type="text" value="" id="text1" name="text1" style="width: 150px;" />
<br />
<input type="button" value="Click Me" id="1" class="answer" data-info="1"/>
<input type="button" value="Click Me" id="2" class="answer" data-info="2"/>
<input type="button" value="Click Me" id="3" class="answer" data-info="3"/>
</form>
<div id="answer_info">
</div>
It works if you delete the last piece of code
$('#text1').trigger('change') {
alert('Changed');
});
I think the best way is to use a String variable instead of a text input, and check its value after each button is clicked, e.g.
var string = "";
$('#1').click(function(e) {
var = var + "1";
$('#1').attr("disabled", true);
checkCode();
});
$('#2').click(function(e) {
var = var + "2";
$('#2').attr("disabled", true);
checkCode();
});
$('#3').click(function(e) {
var = var + "3";
$('#3').attr("disabled", true);
checkCode();
});
I'm not a 100% sure this works correctly or if it causes an error on:
$(text1).val($(text1)+$(this).id); // might cause an error
code:
$(document).on('click','#1',function()){
$(text1).val($(text1)+$(this).id);
}
$(document).on('click','#2',function()){
$(text1).val($(text1)+$(this).id);
}
$(document).on('click','#3',function()){
$(text1).val($(text1)+$(this).id);
}
$(document).on('change','#text1'){
alert('Changed to: '+$(this).val());
});
Can you try this, and see if this works?

PHP code not working in a Form which is used for javascript

I am working with a form which uses Javascript for a process. When i try to read the textbox value in form with PHP, It's not showing output.
My code is
HTMLCode is
<form class="form-inline" method="POST" action="staff.php" onSubmit=" return questiontable()" >
<div class="form-group">
<label for="qscount">Number of Questions: </label>
<input type="number" name="qscount" class="form-control" id="qscount" style="width:150px;" placeholder="No of questions"> <br>
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary" id="gobtn" onClick="return disable()" >Go</button> <br>
<p id="btnhide"> </p>
</div>
</form>
Javascript is
<script type="text/javascript">
function questiontable()
{
var qs = document.getElementById("qscount").value;
var count;
for(count=1; count<=qs; count++)
{
document.getElementById("demo").innerHTML += '<br><font style="font-size: 20px">'+ count+'. <input class="textboxtest" style="width:850px;" type="text" name=" q'+ count +' " placeholder="Question "><br>' ;
document.getElementById("demo").innerHTML +='<br><input style="margin-left: 25px;" type="radio" name="a'+count+'" value="c1"> <input class="testbox" type="text" name="o'+count+'1" placeholder="Option 1">';
return false;
}
</script>
PHP Code is
<?php
if (isset($_POST['qscount'])){
echo $_POST['qscount'];
}
?>
I want to use this qscount value in another php page. How to get this textbox value in PHP and use it in another page ?
Javascript function() should return true, since you are using return function() in onclick attribute of button type=submit
<script type="text/javascript">
function questiontable()
{
var qs = document.getElementById("qscount").value;
var count;
for(count=1; count<=qs; count++)
{
document.getElementById("demo").innerHTML += '<br><font style="font-size: 20px">'+ count+'. <input class="textboxtest" style="width:850px;" type="text" name=" q'+ count +' " placeholder="Question "><br>' ;
document.getElementById("demo").innerHTML +='<br><input style="margin-left: 25px;" type="radio" name="a'+count+'" value="c1"> <input class="testbox" type="text" name="o'+count+'1" placeholder="Option 1">';
}
return true;
}
</script>
This will continue the form posting onclick of the button
If you are trying to create the number of questions on click dynamically using javascript,
then use syntax to call questionTable
<button type="button" class="btn btn-primary" id="gobtn" onClick="javascript:return questiontable()" >Create Questions</button>
Remove
onSubmit=" return questiontable()"
from the form
Now when the question table is rendered, please show the button type="submit"
<button type=submit value="Go" name="cmdGo">Go</button>
to trigger form submission
Hope it helps!

Javascript dynamically created form field validation

I have created a form with a dynamically created field and i am trying to find a way to validate all the fields with javascript. I just want to alert the user that a field is null. Here is my code:
<script>
var counter = 0;
function addInput(divName){
counter++;
var Ai8ousa = document.createElement('div');
Ai8ousa.innerHTML = "Field: "+(counter +1) + "<input type='text' name='field[]'>";
document.getElementById(divName).appendChild(Ai8ousa);
}
function validations(form){
var field;
var i=0;
do{
field=form['field[]'];
if (field.value=='')
{
alert('The field is null!!!');
return false;
}
i++;
}while(i<counter);
}
</script>
<form action="" method="post" onsubmit="return validations(this)" >
<div id="dynamicInput">
Field : <input type="text" name="field[]" /> <br />
</div>
<input type="button" value="New field" onClick="addInput('dynamicInput');">
<input type="submit" value="Submit" />
</form>
I was expecting that will work but i was obviously wrong:(
With this code if i haven't pressed the "New field" button and press submit i will get the alert as expected. But on all other cases i am not getting anything!
Thanks for your time anyway, and sorry if i have made grammar mistakes!
<script type="text/javascript">
var counter = 0;
function addInput(divName){
counter++;
var Ai8ousa = document.createElement('div');
Ai8ousa.innerHTML = "Field: "+(counter +1) + "<input type='text' name='field[]'>";
document.getElementById(divName).appendChild(Ai8ousa);
}
function validations(form){
var field;
var i=0;
do{
field=form[i];
if (field.value=='')
{
alert('The field is null!!!');
return false;
}
i++;
}while(i<counter);
}
</script>
<form action="" method="post" onsubmit="return validations(this)" >
<div id="dynamicInput">
Field : <input type="text" name="field[]" /> <br />
</div>
<input type="button" value="New field" onClick="addInput('dynamicInput');">
<input type="submit" value="Submit" />
</form>
I don't understand this line: field=form['field[]'];, so I changed it to field=form[i];
http://jsfiddle.net/sZ4sd/

Categories

Resources