How to add name attribute of input field dynamically using Javascript/Jquery - javascript

I need one help.I need to add input field name attribute dynamically using Javascript/Jquery. I am each time creating new field by clicking on + button and delete the required field by clicking on - button.I am explaining my code below.
function createNew(evt){
$('#questionshowp1').append('<div class="form-group"><input name="questions1" id="questions1" class="form-control firstsec" placeholder="Text, Image URL, or LaTeX" value="" type="text"><div class="secondsec"><button type="button" class="btn btn-sm btn-success exp-add" style="line-height:12px;" onclick="createNew(this);"><i class="fa fa-plus" aria-hidden="true"></i></button><button type="button" class="btn btn-sm btn-danger exp-minus" style="line-height:12px;" onclick="deleteNew(this)"><i class="fa fa-minus" aria-hidden="true"></i></button></div></div>');
$(evt).css('display', 'none');
$(evt).siblings("button.btn-danger").css('display', 'block');
}
function deleteNew(evnt){
$(evnt).closest(".form-group").remove();
}
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>
<div class="questionshowp" id="questionshowp1">
<div class="form-group">
<input name="questions0" id="questions0" class="form-control firstsec" placeholder="Text, Image URL, or LaTeX" value="" type="text">
<div class="secondsec">
<button type="button" class="btn btn-sm btn-success exp-add" style="line-height:12px;" onclick="createNew(this);"><i class="fa fa-plus" aria-hidden="true"></i></button>
<button type="button" class="btn btn-sm btn-danger exp-minus" style="line-height:12px;display:none;" onclick="deleteNew(this)"><i class="fa fa-minus" aria-hidden="true"></i></button>
</div>
</div>
</div>
Here i am creating new field using + button and here i need to increment the name attribute value like questions0,questions1,questions2.... this.Suppose user delete any field then also this given order will remain with all field as name attribute value.Please help me.

Have a look attached snippet.
function createNew(evt){
var cur=$("input:text").length+1;
$('#questionshowp1').append('<div class="form-group"><input name="questions'+cur+'" id="questions1" class="form-control firstsec" placeholder="Text, Image URL, or LaTeX" value="" type="text"><div class="secondsec"><button type="button" class="btn btn-sm btn-success exp-add" style="line-height:12px;" onclick="createNew(this);">+<i class="fa fa-plus" aria-hidden="true"></i></button><button type="button" class="btn btn-sm btn-danger exp-minus" style="line-height:12px;" onclick="deleteNew(this)">-<i class="fa fa-minus" aria-hidden="true"></i></button></div></div>');
$(evt).css('display', 'none');
$(evt).siblings("button.btn-danger").css('display', 'block');
var i=0;
$('input[type="text"]').each(function(){
$(this).attr('name', 'questions' + i);
$(this).attr('id', 'questions' + i);
i++;
});
}
function deleteNew(evnt){
$(evnt).closest(".form-group").remove();
var i=0;
$('input[type="text"]').each(function(){
$(this).attr('name', 'questions' + i);
$(this).attr('id', 'questions' + i);
i++;
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="questionshowp" id="questionshowp1">
<div class="form-group">
<input name="questions0" id="questions0" class="form-control firstsec" placeholder="Text, Image URL, or LaTeX" value="" type="text">
<div class="secondsec">
<button type="button" class="btn btn-sm btn-success exp-add" style="line-height:12px;" onclick="createNew(this);">+<i class="fa fa-plus" aria-hidden="true"></i></button>
<button type="button" class="btn btn-sm btn-danger exp-minus" style="line-height:12px;display:none;" onclick="deleteNew(this)">-<i class="fa fa-minus" aria-hidden="true"></i></button>
</div>
</div>
</div>

First of all, your aproach is pretty bad. It's not a good idea to put everything in a long string and place it somewhere in your JS. But, this is not your question.
Just create a new variable in your script for counting.
var count = 0;
And then increase the count in your createNew function and place the value everywhere you need it in your element string.
++count;
'<input name="questions' + count + '" id="questions' + count + '"'
That's it.

You simply have to count the number of clicks
and use that count in your script to have unique name attributes.
<script type="text/javascript">
var clicks = 0;
function createNew() {
clicks += 1;
var ques = "questions" + clicks;
$('#questionshowp1').append('<div class="form-group"><input name='+ques+' id="questions1" class="form-control firstsec" placeholder="Text, Image URL, or LaTeX" value="" type="text"><div class="secondsec"><button type="button" class="btn btn-sm btn-success exp-add" style="line-height:12px;" onclick="createNew(this);"><i class="fa fa-plus" aria-hidden="true"></i></button><button type="button" class="btn btn-sm btn-danger exp-minus" style="line-height:12px;" onclick="deleteNew(this)"><i class="fa fa-minus" aria-hidden="true"></i></button></div></div>');
$(evt).css('display', 'none');
$(evt).siblings("button.btn-danger").css('display', 'block');
};
</script>

Create a global variable idCount in your script and in createNew function increment its value.
var idCount = 0;
function createNew(evt){
idCount++;
$('#questionshowp1').append('<div class="form-group"><input name="questions'+idCount+'" id="questions1" class="form-control firstsec" placeholder="Text, Image URL, or LaTeX" value="" type="text"><div class="secondsec"><button type="button" class="btn btn-sm btn-success exp-add" style="line-height:12px;" onclick="createNew(this);">+<i class="fa fa-plus" aria-hidden="true"></i></button><button type="button" class="btn btn-sm btn-danger exp-minus" style="line-height:12px;" onclick="deleteNew(this)">-<i class="fa fa-minus" aria-hidden="true"></i></button></div></div>');
$(evt).css('display', 'none');
$(evt).siblings("button.btn-danger").css('display', 'block');
}
function deleteNew(evnt){
$(evnt).closest(".form-group").remove();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="questionshowp" id="questionshowp1">
<div class="form-group">
<input name="questions0" id="questions0" class="form-control firstsec" placeholder="Text, Image URL, or LaTeX" value="" type="text">
<div class="secondsec">
<button type="button" class="btn btn-sm btn-success exp-add" style="line-height:12px;" onclick="createNew(this);">+<i class="fa fa-plus" aria-hidden="true"></i></button>
<button type="button" class="btn btn-sm btn-danger exp-minus" style="line-height:12px;display:none;" onclick="deleteNew(this)">-<i class="fa fa-minus" aria-hidden="true"></i></button>
</div>
</div>
</div>

Related

Submitting form twice using Ajax

I am trying to submit the form using Ajax, but it submitted the entered values twice. Could you please help me to prevent this issue? I tried several suggestions from the previous questions, but it did not work.
Thank you
Html Code:
<form id="ratingForm" method="POST">
<div class="form-group">
<h4>Rate this product</h4>
<!-- Start Star -->
<button type="button" class="btn btn-warning btn-sm rateButton" aria-label="Left Align">
<span class="glyphicon glyphicon-star" aria-hidden="true"></span>
</button>
<button type="button" class="btn btn-default btn-grey btn-sm rateButton" aria-label="Left Align">
<span class="glyphicon glyphicon-star" aria-hidden="true"></span>
</button>
<button type="button" class="btn btn-default btn-grey btn-sm rateButton" aria-label="Left Align">
<span class="glyphicon glyphicon-star" aria-hidden="true"></span>
</button>
<button type="button" class="btn btn-default btn-grey btn-sm rateButton" aria-label="Left Align">
<span class="glyphicon glyphicon-star" aria-hidden="true"></span>
</button>
<button type="button" class="btn btn-default btn-grey btn-sm rateButton" aria-label="Left Align">
<span class="glyphicon glyphicon-star" aria-hidden="true"></span>
</button>
<!-- End Star -->
<input type="hidden" id="rating" name="rating" value="1">
<input type="hidden" id="itemId" name="itemId" value="<?php echo $_GET['id']; ?>">
<input type="hidden" name="action" value="saveRating">
</div>
<div class="form-group">
<!--Comment Start-->
<label for="usr">Title*</label>
<input type="text" id="title" name="title" required>
</div>
<div class="form-group">
<label for="comment">Comment*</label>
<textarea rows="5" id="comment" name="comment" required></textarea>
</div>
<div class="form-group">
<button type="submit" class="btn btn-info" id="saveReview">Save Review</button>
</div>
<!--Comment End-->
</form>
Js Code:
$('#ratingForm').on('submit', function(event){
event.preventDefault();
event.stopImmediatePropagation();
var formData = $(this).serialize();
$.ajax({
type : 'POST',
dataType: "json",
url : 'action.php',
data : formData,
success:function(response){
if(response.success == 1) {
$("#ratingForm")[0].reset();
window.location.reload();
}
}
});
});
Php Code (This is action.php file):
Execution.php file inserts data into database using mysql.
<?php
session_start();
include 'class/Execution.php';
$rating = new Rating();
if(!empty($_POST['action']) && $_POST['action'] == 'saveRating'
&& !empty($_POST['rating'])
&& !empty($_POST['itemId'])) {
$rating->saveRating($_POST, $_SESSION['userId']);
$data = array(
"success" => 1,
);
echo json_encode($data);
}
?>
with the POST method your form may be submitting second time when it reload with window.location.reload(); you can simply redirect the page when ajax call successfully with window.location.href = "http://yourwebpage.php"; or window.location.replace("http://yourwebpage.php");
Can you try the below code
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Js Check</title>
<script src="https://code.jquery.com/jquery-3.5.1.min.js" language="javascript"></script>
</head>
<body>
<div id="wrapper">
<form id="ratingForm" method="POST">
<div class="form-group">
<h4>Rate this product</h4>
<!-- Start Star -->
<button type="button" class="btn btn-warning btn-sm rateButton" aria-label="Left Align"> <span class="glyphicon glyphicon-star" aria-hidden="true"></span> </button>
<button type="button" class="btn btn-default btn-grey btn-sm rateButton" aria-label="Left Align"> <span class="glyphicon glyphicon-star" aria-hidden="true"></span> </button>
<button type="button" class="btn btn-default btn-grey btn-sm rateButton" aria-label="Left Align"> <span class="glyphicon glyphicon-star" aria-hidden="true"></span> </button>
<button type="button" class="btn btn-default btn-grey btn-sm rateButton" aria-label="Left Align"> <span class="glyphicon glyphicon-star" aria-hidden="true"></span> </button>
<button type="button" class="btn btn-default btn-grey btn-sm rateButton" aria-label="Left Align"> <span class="glyphicon glyphicon-star" aria-hidden="true"></span> </button>
<!-- End Star -->
<input type="hidden" id="rating" name="rating" value="1">
<input type="hidden" id="itemId" name="itemId" value="<?php echo $_GET['id']; ?>">
<input type="hidden" name="action" value="saveRating">
</div>
<div class="form-group">
<!--Comment Start-->
<label for="usr">Title*</label>
<input type="text" id="title" name="title" required>
</div>
<div class="form-group">
<label for="comment">Comment*</label>
<textarea rows="5" id="comment" name="comment" required></textarea>
</div>
<div class="form-group">
<button type="submit" class="btn btn-info" id="saveReview">Save Review</button>
</div>
<!--Comment End-->
</form>
</div>
<script>
jQuery(document).ready(function($) {
$('#ratingForm').on('submit', function(event){
event.preventDefault();
event.stopImmediatePropagation();
var formData = $(this).serialize();
$.ajax({
type : 'POST',
dataType: "json",
url : 'action.php',
data : formData,
success:function(response){
console.log(response);
if(response.success == 1) {
$("#ratingForm")[0].reset();
window.location.reload();
}
}
});
});
});
</script>
</body>
</html>

Conditional statement based on value of attributes in laravel blade

i want to make if else statement based on the input id of select given
here is my code
my attribute id
<select name="cu" id="cu" class="input-sm form-control" onchange="">
My if else condition
#if(??)
<a class="btn btn-sm btn-default pull-right" type="button"
title="Search Category" onclick="openNewWindow('{{ route('reporting.') }}')" >
<i class="fa fa-hand-o-up"></i> Choose Category</a>
#else
<a class="btn btn-sm btn-default pull-right" type="button" title="Search Category"
onclick="openNewWindow('{{ route('reporting.categoryCheckBoxList', ['cuid' => '_cuid_']) }}'.replace('_cuid_', document.getElementById('cu').value))" >
<i class="fa fa-hand-o-up"></i> Choose Category</a>
#endif
what source code i need to put inside if statement
The short answer you can't pass selected value (JS variable) to #if() statement (PHP code).
Here is why
On page request: The process flow looks like this:
Server Side PHP code rendering
Response sent to the Browser
Browser begins rendering and executing JS
You would want to hide (using bootstrap d-none class utility) both a tags on page load then on user select "change" event you show/hide your correspondant a tag.
Blade Code
<select name="cu" id="cu" class="input-sm form-control">
<option value="option-value1"> Opt 1</option>
<option value="option-value2"> Opt 2</option>
</select>
//...
<a id="option-value1" class="btn btn-sm btn-default pull-right d-none" type="button"
title="Search Category" onclick="openNewWindow('{{ route('reporting.') }}')" >
<i class="fa fa-hand-o-up"></i> Choose Category</a>
<a id="option-value2" class="btn btn-sm btn-default pull-right d-none" type="button" title="Search Category"
onclick="openNewWindow('{{ route('reporting.categoryCheckBoxList', ['cuid' => '_cuid_']) }}'.replace('_cuid_', document.getElementById('cu').value))" >
<i class="fa fa-hand-o-up"></i> Choose Category</a>
//...
<script>
//...
//make sure you already loaded Jquery
$('select#cu').on('change', function() {
value = this.value;
$("a#" + value).show();
$("a id[value!='" + value + "']").hide();
});
</script>
You cannot pass js value inside php. You can achieve the same result using Jquery show and hide element:
<select name="cu" id="cu" class="input-sm form-control" onchange="showLink(this.value)">
<a style="display:none" id="first" class="btn btn-sm btn-default pull-right" type="button"
title="Search Category" onclick="openNewWindow('{{ route('reporting.') }}')">
<i class="fa fa-hand-o-up"></i> Choose Category</a>
<a style="display:none" id="second" class="btn btn-sm btn-default pull-right" type="button" title="Search Category"
onclick="openNewWindow('{{ route('reporting.categoryCheckBoxList', ['cuid' => '_cuid_']) }}'.replace('_cuid_', document.getElementById('cu').value))">
<i class="fa fa-hand-o-up"></i> Choose Category</a>
<script>
function showLink(value) {
if (value == < your value >)
{
$("#first").show();
$("#second").hide();
}
else
{
$("#second").show();
$("#first").hide();
}
}
</script>

one search input multiple names

So I am working on a website where you have one search bar and you can search with multiple websites like google, amazon, youtube and some more. My problem is, that all this is in one form and I can't use the name="q" which is working on the most search api's on amazon and wikipedia, because there are the names k (amazon) and search (wikipedia). Does anyone know how to change the name f the input for two buttons?
Here's the link: https://multi-search.bss.design/
<form target="_blank">
<input class="form-control visible" type="search" name="q" autofocus="" autocomplete="off" id="input" placeholder="Search...">
<button class="btn btn-primary btn-circle" type="submit" value="Google" formaction="http://www.google.de/search" target="_blank" value="Google"><span><i class="fa fa-google animated" ></i></span></button>
<button class="btn btn-primary btn-circle" type="submit" value="YouTube" formaction="https://www.youtube.com/search" target="_blank"><span><i class="fa fa-youtube-play animated"></i></span></button>
<button class="btn btn-primary btn-circle" type="submit" value="Amazon" formaction="https://www.amazon.de/s/" target="_blank"><span><i class="fa fa-amazon animated"></i></span></button>
<button class="btn btn-primary btn-circle" type="submit" value="Google Translate" formaction="https://translate.google.com/#auto/de/" target="_blank"><span><i class="fas fa-language animated"></i></span></button>
<button class="btn btn-primary btn-circle" type="submit" value="Google Images" formaction="http://www.google.com/images?q"><span><i class="fa fa-image animated"></i></span></button>
<button class="btn btn-primary btn-circle" type="submit" value="Netflix" formaction="https://www.netflix.com/search?q"><span><i class="fa fa-film animated"></i></span></button>
<button class="btn btn-primary btn-circle" type="submit" value="Wikipedia" formaction="https://en.wikipedia.org/w/index.php?"><span><i class="fa fa-wikipedia-w animated"></i></span></button>
</form>
You could simply store a data- attribute on each button representing the corresponding name attribute (defaulting to q) and change it dynamically upon click.
e.g. :
<button ... type="submit" value="Wikipedia" data-search-input-name="search">
document.querySelectorAll('button[type="submit"]').forEach(function(submitButton) {
submitButton.addEventListener('click', function(e) {
document.querySelector('[data-input-search]').setAttribute('name',
this.getAttribute('data-search-input-name') || 'q');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input data-input-search class="form-control visible" type="search" name="q" autofocus="" autocomplete="off" id="input" placeholder="Search...">
<button class="btn btn-primary btn-circle" type="submit" value="Google" formaction="http://www.google.de/search" target="_blank" value="Google"><span><i class="fa fa-google animated" ></i></span>Google</button>
<button class="btn btn-primary btn-circle" type="submit" value="YouTube" formaction="https://www.youtube.com/search" target="_blank"><span><i class="fa fa-youtube-play animated"></i></span>YouTube</button>
<button class="btn btn-primary btn-circle" type="submit" value="Amazon" formaction="https://www.amazon.de/s/" data-search-input-name="k" target="_blank"><span><i class="fa fa-amazon animated"></i></span>Amazon</button>
<button class="btn btn-primary btn-circle" type="submit" value="Google Translate" formaction="https://translate.google.com/#auto/de/" target="_blank"><span><i class="fas fa-language animated"></i></span>Translate</button>
<button class="btn btn-primary btn-circle" type="submit" value="Google Images" formaction="http://www.google.com/images?q"><span><i class="fa fa-image animated"></i></span>Images</button>
<button class="btn btn-primary btn-circle" type="submit" value="Netflix" formaction="https://www.netflix.com/search?q"><span><i class="fa fa-film animated"></i></span>Netflix</button>
<button class="btn btn-primary btn-circle" type="submit" value="Wikipedia" formaction="https://en.wikipedia.org/w/index.php?" data-search-input-name="search"><span><i class="fa fa-wikipedia-w animated"></i></span>Wikipedia</button>
</form>
Note: only Wikipedia button works here as Google/Amazon block that from an iframe, but you can test Wikipedia.
You can for example:
1. Add hidden fields
<input type="search" name="q" onkeyup="updateHiddenFields()">
<input type="hidden" name="k">
and synchronize then using JS code:
const updateHiddenFields = (evt) => {
document.getElementsByName('k')[0].value = document.getElementsByName('q') .[0].value
};
2. Rename field when button is clicked:
document.getElementById('button-amazon')[0].onclick = () => document.getElementsByName('q')[0].setAttribute('name', 'k');
(Add id="button-amazon" to the Amazon button to make this working.)

Is there any alternative to keyUp to check whether an input was filled?

So I have this code:
$(document).ready(function(){
if($('#proofAttach-filemanager').val().length !=0){
$('#download_now').attr('disabled', false);
}
else
{
$('#download_now').attr('disabled', true);
}
});
The field with id proofAttach-filemanager is filled up dynamically using elFinder every time I upload a file.
Since the code above is only running every time the page loads, I don't know how to update the download_now button to enable dynamically every time the field is filled (and without keyUp)
HTML Segment:
<div class="form-group col-md-12">
<label>Attachment</label>
<input type="text" id="proofAttach-filemanager" name="proofAttach" value="" class="form-control" readonly="">
<div class="btn-group" role="group" aria-label="..." style="margin-top: 3px;">
<button type="button" data-inputid="proofAttach-filemanager" class="btn btn-default popup_selector">
<i class="fa fa-cloud-upload"></i> Browse uploads</button>
<button type="button" data-inputid="proofAttach-filemanager" id="download_now" class="btn btn-default download_now">
<i class="fa fa-cloud-download"></i> Download</button>
<button type="button" data-inputid="proofAttach-filemanager" class="btn btn-default clear_elfinder_picker">
<i class="fa fa-eraser"></i> Clear</button>
</div>
Writing your logic inside the change event of that text box should work.
$(document).ready(function(){
toggleDownloadButtonAccess();
$('#proofAttach-filemanager').change(toggleDownloadButtonAccess);
function toggleDownloadButtonAccess(){
var $btnDownload = $('#download_now');
if($('#proofAttach-filemanager').val().length !=0){
$btnDownload.attr('disabled', false);
}
else
{
$btnDownload.attr('disabled', true);
}
}
});

Trying to make a virtual keypad in Bootstrap using JS

There's a simple textbox with a virtual keypad that toggles in and out as the user clicks the keyboard icon inside of the text box:
each letter is a clickable button and the idea is to populate the text box with the value of the button being clicked. Here's what I've done:
HTML
<div class="input-group col-md-4 col-md-offset-4">
<input id="word" type="textbox" placeholder="Enter your word here..." class="form-control input-lg">
<span class="fa fa-keyboard-o fa-2x lookup-icon"></span>
<span class="input-group-btn"><button class="btn btn-lg btn-primary" type="button" id="lookup">Lookup</button></span>
</div>
<div id="virtualkeypad" class="col-md-offset-4 hidden">
<button id="key" class="btn btn-lg special-char-btn first-btn" type="button">á</button>
<button id="key" class="btn btn-lg special-char-btn" type="button">é</button>
<button id="key" class="btn btn-lg special-char-btn" type="button">í</button>
<button id="key" class="btn btn-lg special-char-btn" type="button">ó</button>
<button id="key" class="btn btn-lg special-char-btn" type="button">ú</button>
<button id="key" class="btn btn-lg special-char-btn" type="button">ü</button>
<button id="key" class="btn btn-lg special-char-btn last-btn" type="button">ñ</button>
</div>
JS
function toggler(divId) {
$("#" + divId).toggleClass("hidden show");
}
$(function(){
var $write = $('#word');
$('#key').click(function(){
var $this = $(this),
character = $this.html();
$write.html($write.html() + character);
});
});
However, I must be doing something very wrong because the above code doesn't seem to do anything. Could someone please help me fix it?
Update: As advised by sandeep s in his answer below, I removed the key ID from the buttons and added a new class spl-key instead. The HTML now looks like this:
<div class="input-group col-md-4 col-md-offset-4">
<input id="word" type="textbox" placeholder="Enter your word here..." class="form-control input-lg">
<span class="fa fa-keyboard-o fa-2x lookup-icon"></span>
<span class="input-group-btn"><button class="btn btn-lg btn-primary" type="button" id="lookup">Lookup</button></span>
</div>
<div id="virtualkeypad" class="col-md-offset-4 hidden">
<button class="spl-key btn btn-lg special-char-btn first-btn" type="button">á</button>
<button class="spl-key btn btn-lg special-char-btn" type="button">é</button>
<button class="spl-key btn btn-lg special-char-btn" type="button">í</button>
<button class="spl-key btn btn-lg special-char-btn" type="button">ó</button>
<button class="spl-key btn btn-lg special-char-btn" type="button">ú</button>
<button class="spl-key btn btn-lg special-char-btn" type="button">ü</button>
<button class="spl-key btn btn-lg special-char-btn last-btn" type="button">ñ</button>
</div>
And I also changed the script as advised to:
function toggler(divId) {
$("#" + divId).toggleClass("hidden show");
}
$(function(){
$('.spl-key').click(function(e){
$(e.target).toggleClass("hidden");
character = $(e.target).text();
$('#word').val(character);
});
});
The problem, however, persists and button clicks are still unresponsive as before.
This should be your implementation:
$(function(){
$('.btn-lg').click(function(e){
$(e.target).toggleClass("hidden");
character = $(e.target).text();
$('#word').val(character);
});
});

Categories

Resources