Keyup not working for dynamically added input-groups - javascript

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>

Related

how to create a search feature without clicking the search button?

how to create a search feature without clicking the search button? so when entering a value then enter can immediately bring up the search results.
index.blade.php
<div class="input-group col-10">
<input type="text" class="form-control search-bar" id="search-bar" placeholder="Type to search course">
<div class="input-group-append">
<button class="btn btn-primary form-control btn-search">Search</button>
</div>
</div>
index_script.blade.php
$(".btn-search").click(function() {
$(".see-more").click();
$(".see-more").remove();
var value = $(".search-bar").val().toLowerCase();
$(".course-item").filter(function() {
$(this).toggle($(this).text().toLowerCase().indexOf(value) > -1);
});
$(".owl-item").filter(function() {
$(this).toggle($(this).text().toLowerCase().indexOf(value) > -1);
});
$.each($("#ajar-catalog-container .owl-stage"), function() {
var count = 0;
$.each($(this).children('.owl-item'), function() {
display = $(this).children().css('display');
if (display == 'block') {
count++;
}
});
if(count == 0) {
$(this).closest('.card').css('display', 'none');
}
else {
$(this).closest('.card').css('display', 'block');
}
});
});
please help, thank you
just manually trigger the click event of the button element.
$("#search-bar").keydown(function(e){
if (e.keyCode == 13) {
$(".btn-search").click();
}
});
Method #1
You can use the oninput event in JavaScript to get the results when entering a value to the input field.
var searchInput = document.getElementById("search-bar")
searchInput.oninput = function(){
// put your logic for search filter here
}
<div class="input-group col-10">
<input type="text" class="form-control search-bar" id="search-bar" placeholder="Type to search course">
<div class="input-group-append">
<button class="btn btn-primary form-control btn-search">Search</button>
</div>
</div>
Method #2 -
You can use jQuery's keydown() event
$("#search-bar").keydown(function(){
// your logic here
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="input-group col-10">
<input type="text" class="form-control search-bar" id="search-bar" placeholder="Type to search course">
<div class="input-group-append">
<button class="btn btn-primary form-control btn-search">Search</button>
</div>
</div>

How to create a 'add more' feature in HTML forms [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I am creating a HTML form in which I need to create a 'add more' button so another field appears. Any help would be appreciated
This isn't possible in pure HTML, but it can easily be achieved using javascript!
Basic example
In the basic example, you have one input field. When you click the add field button an extra input gets added after the last inserted input.
$(document).on('click', '.add_field', function() {
$('<input type="text" class="input" name="field[]" value="">').insertAfter('.input:last');
})
form {
padding: 20px;
}
input {
width: 100%;
margin-bottom: 5px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<input type="text" class="input" name="field[]" value="">
</form>
<button type="button" class="add_field">Add field</button>
Copy value
This example is almost the same as the example above with one difference. It copies the value of the previous input. This is done with help of the JQuery .val() method
$(document).on('click', '.add_field', function() {
let value = $('.input:last').val(); // gets the value of the previous input
$('<input type="text" class="input" name="field[]" value="' + value + '">').insertAfter('.input:last');
})
form {
padding: 20px;
}
input {
width: 100%;
margin-bottom: 5px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<input type="text" class="input" name="field[]" value="">
</form>
<button type="button" class="add_field">Add field</button>
Input groups
You could also copy an entire input group with multiple input fields.
$(document).on('click', '.add_field', function() {
$('<div class="input-group"><input type="email" class="input" name="email[]" value="" placeholder="Your email"><input type="password" class="input" name="password[]" value="" placeholder="Your password"></div>').insertAfter('.input-group:last');
})
form {
padding: 20px;
}
input {
width: 100%;
margin-bottom: 5px;
}
.input-group {
border-bottom: 1px solid gray;
padding: 5px 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<div class="input-group">
<input type="email" class="input" name="email[]" value="" placeholder="Your email">
<input type="password" class="input" name="password[]" value="" placeholder="Your password">
</div>
</form>
<button type="button" class="add_field">Add field</button>
If you need any more examples please leave a comment!
Please try instead,
$(".Addmore").click(function(e) {
e.preventDefault();
// make a separation line
$("#FormItems").append('<hr width="300px">');
// append the input field as your needs
$("#FormItems").append('<input name="user" type="text" placeholder="Username"><br>');
$("#FormItems").append('<input name="email" type="email" placeholder="Email Address">');
});
.formwrapper{
text-align:center;
}
input{
padding:3px;
margin-bottom:5px;
display:inline-block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="formwrapper">
<form>
<div id="FormItems">
<input name="user" type="text" placeholder="Username"><br>
<input name="email" type="email" placeholder="Email Address">
</div>
<input type="button" value="Add More" class="Addmore">
<input type="submit" value="Submit">
</form>
</div>
In a few lines of js and html you can get that :
<button class="add-input">Add one more input</button>
<form action="." method="GET">
<div class="inputs">
<input type="text" name="text[]">
</div>
<input type="submit" value="submit">
</form>
<script>
const addButton = document.querySelector('button.add-input')
const inputDiv = document.querySelector('form .inputs')
addButton.addEventListener('click', ()=>{ // button to add the inputs
let newInput = document.createElement('input')
newInput.name = 'text[]' // add the name of the input
newInput.type = 'text' // add the type of the input
// you can add other attributes before appeding the node into the html
inputDiv.appendChild(newInput)
})
</script>
and you will have this as a result (I used php to prompt the result)
you can add as many input you want/need.
Next step is just doing some css
I hope this is, what you mean
<form>
<input type="text">
<input type="submit" value="cta">
</form>
<button>Add More</button>
<script>
document.querySelector('button').addEventListener('click', () => {
let field = document.createElement('input');
// change field however you'd like
document.querySelector('form').insertBefore(field, document.querySelector('form:last-child'));
})
</script>
You cannot create this using HTML only, you will need javascript. You could use a frontend framework like react.js to make life easy.
For example in react, you could bind an onclick listener on the button and maintain an array of values as state. Use this array to map value to your input. Whenever user clicks the button, you can then simply push a defaultValue to the array and react will handle the rest.
Import React, { useState } from 'react';
const Page = ()=>{
const [ arr, setArr ] = useState([""]);
const handleAdd = ()=>{
setArr([...arr, ""]);
};
return <form>
{arr.map((elem, index)=><input
onChange={ //"implement logic to update value stored in array" }
value={elem}
key={index} /> )}
<button onClick={()=>handleAdd()}>Add</button>
</form>
}
Using Bootstrap and jquery
Only in html is not possible, you need some on click event to trigger the functionality that may change the html dom.
You can use vanilla javascript as well, here is example using jquery library.
It will dynamically add and remove the element
index.html
<!DOCTYPE html>
<html>
<head>
<title>YDNJSY</title>
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
<script src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.0/js/bootstrap.min.js"></script>
<script src="//code.jquery.com/jquery-1.11.1.min.js"></script>
</head>
<body>
<!-- <h1>Lets learn javascript</h1> -->
<div class="col-xs-12">
<div class="col-md-12">
<h3> Actions</h3>
<div id="field">
<div id="field0">
<!-- Text input-->
<div class="form-group">
<label class="col-md-4 control-label" for="action_id">Action Id</label>
<div class="col-md-5">
<input id="action_id" name="action_id" type="text" placeholder=""
class="form-control input-md">
</div>
</div>
<br><br>
<!-- Text input-->
<div class="form-group">
<label class="col-md-4 control-label" for="action_name">Action Name</label>
<div class="col-md-5">
<input id="action_name" name="action_name" type="text" placeholder=""
class="form-control input-md">
</div>
</div>
<br><br>
</div>
</div>
<!-- Button -->
<div class="form-group">
<div class="col-md-4">
<button id="add-more" name="add-more" class="btn btn-primary">Add More</button>
</div>
</div>
<br><br>
</div>
</div>
</body>
<script src="./index.js"></script>
</html>
index.js
$(document).ready(function () {
var next = 0;
$("#add-more").click(function (e) {
e.preventDefault();
var addto = "#field" + next;
var addRemove = "#field" + (next);
next = next + 1;
var newIn = ' <div id="field' + next + '" name="field' + next + '"><!-- Text input--><div class="form-group"> <label class="col-md-4 control-label" for="action_id">Action Id</label> <div class="col-md-5"> <input id="action_id" name="action_id" type="text" placeholder="" class="form-control input-md"> </div></div><br><br> <!-- Text input--><div class="form-group"> <label class="col-md-4 control-label" for="action_name">Action Name</label> <div class="col-md-5"> <input id="action_name" name="action_name" type="text" placeholder="" class="form-control input-md"> </div></div><br><br></div>';
var newInput = $(newIn);
var removeBtn = '<button id="remove' + (next - 1) + '" class="btn btn-danger remove-me" >Remove</button></div></div><div id="field">';
var removeButton = $(removeBtn);
$(addto).after(newInput);
$(addRemove).after(removeButton);
$("#field" + next).attr('data-source', $(addto).attr('data-source'));
$("#count").val(next);
$('.remove-me').click(function (e) {
e.preventDefault();
var fieldNum = this.id.charAt(this.id.length - 1);
var fieldID = "#field" + fieldNum;
$(this).remove();
$(fieldID).remove();
});
});
});

How to check if at least one input is completed?

I have this sample:
link
CODE HTML:
<form class="add-patient">
<fieldset style="display: block;">
<label for="new_exam">New exam</label>
<input type="text" name="new_exam" id="new_exam" value="">
</fieldset>
<fieldset style="display: block;">
<label for="x_ray">X ray</label>
<input type="text" name="x_ray" id="x_ray" value="">
</fieldset>
<input type="button" class="btn btn-submit" onclick="sendForm();" value="Create report">
</form>
CODE JS:
function sendForm() {
var status_form = false;
$(".add-patient input").each(function(){
if($(this).val() == ""){
status_form = true;
}
});
console.log(status_form);
var createdBy = jQuery('#created_by').val();
if( status_form )
{
alert('Fill at least one field');
}else{
alert("now it's ok");
}
}
I want to do a check ... if an input is complete when displaying the message "it; s ok" ... otherwise displaying another message
probably means the code clearly what they want to do.
You can help me with a solution please?
Thanks in advance!
Use .filter to get the length of the input elements having value as ''
Try this:
function sendForm() {
var elem = $(".add-patient input[type='text']");
var count = elem.filter(function() {
return !$(this).val();
}).length;
if (count == elem.length) {
alert('Fill at least one field');
} else {
alert("now it's ok");
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<form class="add-patient">
<fieldset style="display: block;">
<label for="new_exam">New exam</label>
<input type="text" name="new_exam" id="new_exam" value="">
</fieldset>
<fieldset style="display: block;">
<label for="x_ray">X ray</label>
<input type="text" name="x_ray" id="x_ray" value="">
</fieldset>
<input type="button" class="btn btn-submit" onclick="sendForm();" value="Create report">
</form>

How to add text field to multi list - jQuery?

I am trying to take user inputed values and add them to a list. I need to check my list to see if it exists first. I am failing at step one, how do I add the value to the list?
This is my code:
HTML:
<form action="">
<div class="device_item">
<label for="dev_name">Device Name</label>
<input id="dev_name" type="text">
</div>
<div class="device_item">
<label for="dev_name">Device Type</label>
<input id="dev_type" type="text">
</div>
<div class="device_item">
<label for="dev_os">Device OS</label>
<input id="dev_os" type="text">
</div>
<div class="device_item">
<div class="device_info">
<div class="device_info_header">
<label>Device Information Header</label>
<div>
<select multiple="multiple" id="lstBox1" name="device_info_header">
<option value="net_info">Network Info</option>
<option value="os_info">OS Info</option>
<option value="drive_info">Drive Info</option>
<option value="time_dif">Time Difference Info</option>
</select>
</div>
<div id="arrows">
<input type='button' class="delete" value=' < ' />
<input type='button' class='add' value=' > ' />
</div>
<div>
<select multiple="multiple" id="lstBox2" name="device_info_header"></select>
</div>
<input type="text" name="other_info" id="dev_info_other_text" style="display:none;">
<div class="clear_both" />
<div class="other_ops">Other:
<input id="other_field" type="text" />
<input type="button" class="add2" value=' > ' />
</div>
<br>
<br>NEXT BUTTON (creates headers or dictionary keys) TAKES YOU TO:
<br>
<br>TITLE (eg. Net Info, or OS Info)
<br>Key:
<input type="text">
<br>Value:
<input type="text">
<br>Add more button
<br>
<br>next button (loop through the headers/keys).
<br>
<br>finally, a submit button</div>
</div>
</div>
</form>
JS
$(document).ready(function () {
$('.add').click(function (e) {
var selectedOpts = $('#lstBox1 option:selected');
if (selectedOpts.length == 0) {
alert("Nothing to move.");
e.preventDefault();
}
$('#lstBox2').append($(selectedOpts).clone());
e.preventDefault();
});
$('.delete').click(function (e) {
var selectedOpts = $('#lstBox2 option:selected');
if (selectedOpts.length == 0) {
alert("Nothing to move.");
e.preventDefault();
}
$(selectedOpts).remove();
e.preventDefault();
});
$('.add2').click(function (e) {
var other_field_str = $('#other_field').val();
alert(other_field_str);
$('#lstBox2').append(other_field_str);
e.preventDefault();
});
});
I also have the code on this fiddle: http://jsfiddle.net/jdell64/8qsda/1/
UPDATED FIDDLE WITH FULL SOLUTION: http://jsfiddle.net/jdell64/8qsda/
You need to create an <option> element containing the Other input.
$('.add2').click(function (e) {
var other_field_str = $('#other_field').val();
alert(other_field_str);
var other_field = $('<option>', {
value: other_field_str,
text: other_field_str
});
$('#lstBox2').append(other_field);
e.preventDefault();
});
FIDDLE

DIV does not show on link with variables

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

Categories