Jquery - dynamically added input field doesn't send value to post - javascript

I have this particular jquery code to add/remove fields on a form and then send its values:
$(document).ready(function() {
$("#add").click(function() {
var intId = $("#reglas div").length + 1;
var fieldWrapper = $('<div class="fieldwrapper" id="field' + intId + '"/>');
var fName = $('<input align="left" type="text" placeholder="Path" class="reglas_wrapper" id="path" name="field1_' + intId + '" required /> ');
var fName2 = $('<input type="text" class="reglas_wrapper" placeholder="TTL" id="ttl" name="field2_' + intId + '" required />');
var removeButton = $('<input align="right" type="button" id="del" class="remove" value="-" /> <br><br>');
removeButton.click(function() {
$(this).parent().remove();
});
fieldWrapper.append(fName);
fieldWrapper.append(fName2);
fieldWrapper.append(removeButton);
$("#reglas").append(fieldWrapper);
});
$("#cache").each(function() {
$(this).qtip({
content: {
text: $(this).next('.tooltiptext')
}
});
});
});
$('#formsite').on('submit', function (e) {
//prevent the default submithandling
e.preventDefault();
//send the data of 'this' (the matched form) to yourURL
$.post('siteform.php', $(this).serialize());
});
In which you can add/remove fields on the Cache section but the form sends every value except those which were added dynamically.
How can I solve it? You can see the posted form data with Firebug.
Here is a JS Fiddle for you: http://jsfiddle.net/34rYv/121/
Also I realized that when I delete fields, its name doesn't rename.
Maybe you can help me with this too :)
Thanks in advance
Nicolas

Your Cache section stands outside the <form> tags as i see in the source code, so that could be why your fields are not submitted.
Put your form around the left/right div like this:
<div id="wrapper" align="center">
<div class="container" align="center">
<form id="formsite"> // your form starts here
<div id="left">
</div>
<div id="right">
</div>
</form>
</div>
</div>
Instead of this ( what you have right now ):
<div id="wrapper" align="center">
<div class="container" align="center">
<div id="left">
<form id="formsite"> // your form starts here
// the form will automatically be closed in this div
</div>
<div id="right">
</form> // this one will go away
</div>
</div>
</div>
Also, try to keep your code clean, For example:
var fieldWrapper = $('<div></div>',{
class: 'fieldwrapper',
id: 'field'+intId
});
This is way cleaner than:
var fieldWrapper = $('<div class="fieldwrapper" id="field' + intId + '"/>');

Related

How to pass a input text content to a variable

I'm using the Unsplash API in order to input some keywords and then retrieve photos related to those keywords. In order to do that, I'm using the following Javascript:
var APIKey = '{mykey}';
$.getJSON('https://api.unsplash.com/search/photos?query=' + search + '&per_page=19&client_id=' + APIKey, function (data) {
console.log(data);
var imageList = data.results;
$.each(imageList, function (i, val) {
var image = val;
var imageURL = val.urls.regular;
var imageWidth = val.width;
var imageHeight = val.height;
if (imageWidth > imageHeight) {
$('#output').append('<div class="image"><img src="' + imageURL + '"></div>');
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container text-center">
<form class="form-inline" method="post">
<div class="form-group mx-auto my-5">
<input type="text" class="form-control" id="search" placeholder="Search..." name="search">
<button class="btn btn-primary" type="submit">Procurar</button>
</div>
</form>
</div>
<div id="output"></div>
What I'm trying to do is use this input text and this button in order to change the value of the variable search which is on the URL.
I'm new with javascript but I think that what I'm missing is some jQuery syntax.
You need to:
1) Prevent page reload/submitting the form when clicking the button. You can remove the form element as you don't need to refresh the page but get the input text input or keep the form and change the input type from submit to a button one.
2) Hook on the button click event and then execute your GET request to unsplash api.
3) Put this event handler in a document ready event handler so it can trigger when you click the button.
4) Do your magic :)
I hope it helps. Try the snippet below with your API key.
var APIKey = "{mykey}";
$(document).ready(function() {
$("#searchBtn").on("click", function() {
var searchQuery = $("#search").val();
getJson(searchQuery);
});
});
function getJson(search) {
$.getJSON(
"https://api.unsplash.com/search/photos?query=" +
search +
"&per_page=19&client_id=" +
APIKey,
function(data) {
console.log(data);
var imageList = data.results;
$.each(imageList, function(i, val) {
var image = val;
var imageURL = val.urls.regular;
var imageWidth = val.width;
var imageHeight = val.height;
if (imageWidth > imageHeight) {
$("#output").append(
'<div class="image"><img src="' + imageURL + '"></div>'
);
}
});
}
);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container text-center">
<form class="form-inline" method="post">
<div class="form-group mx-auto my-5">
<input type="text" class="form-control" id="search" placeholder="Search..." name="search">
<button id="searchBtn" class="btn btn-primary" type="button">Procurar</button>
</div>
</form>
</div>
<div id="output"></div>

jQuery dynamic fields after validation are disappearing

I have a problem with my jQuery and with validation.
Here is my Code:
var fielddd = 1;
$(document).on('click', '.btn.add-field', function() {
fielddd++;
$('#newfield').append('<textarea class="from-control" name="somename[]" id="field_' + field + '"></textarea>' + '<button class="btn add-field">add</button>' + '<textarea class="from-control" name="somename2[]" id="field_' + field + '"></textarea>');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row">
<textarea class="from-control" name="somename[]" id="field"></textarea>
<button class="btn add-field">add</button>
<textarea class="from-control" name="somename2[]" id="field"></textarea>
</div>
<div class="row" id="newfield">
<!-- new textarea -->
</div>
The problem is that I have an validation and I have an button submit, after checking that one field empty is, the code make and redirect and after this redirect to the same page so that user can give his parameter in textarea. But after this redirect, by the user added field are disappeared.
How can I fix it?
You are using the same id in each and every textarea. Id must be unique. Mistakenly you are using "field" which must be replaced with "fielddd" that is being incremented.
var fielddd = 1;
$(document).on('click', '.btn.add-field', function() {
fielddd++;
$('#newfield').append('<textarea class="from-control" id="field_' + fielddd + '"></textarea>' + '<button class="btn add-field">add</button>' + '<textarea class="from-control" id="field_' + fielddd + '"></textarea>');
});

How To Add two Textbox values with jquery and also add two more textboxs that are apend from the same textboxs

enter image description herethis is simple text boxes i give the value and add them ![enter image description here][2]
when I add more text boxes with append query now the sum is not calculating
[enter image description here][3]
THis is jquery code of iam apending two divs with Two ids and text boxes are also have there ids
Use jquery features for implement complex thing in a very easier way...
It provides Huge Library with number of functions and Flexibility for executing your code in cross browsers
HTML
<div class="row">
<button type="button" class="btn btn-success add-more">ADD MORE</button>
</div>
<div class="form-group" id="ele">
<div class="row" id="item1">
<div class="row">
<input type="number" class="num1">
<label>+</label>
<input type="number" class="num2">
<label>SUM</label>
<input type="number" class="sum" readonly="true">
<button type="button" class="btn btn-success remove">x</button>
</div>
</div>
</div>
JQUERY Script
var item = $('#item1').html();
var cnt = 0;
$('.add-more').click(function() {
cnt++;
$('#ele').append("<div class='row' id='item" + cnt + "'>" + item + "</div>");
});
$(document).on('click', '.remove', function() {
$(this).closest('.row').remove();
});
$(document).on('keyup', '.num1,.num2', function() {
if ($(this).hasClass('num1')) {
var num1 = parseInt($(this).val());
var num2 = parseInt($(this).siblings('.num2').val());
$(this).siblings('.sum').val(num1 + num2);
} else if ($(this).hasClass('num2')) {
var num2 = parseInt($(this).val());
var num1 = parseInt($(this).siblings('.num1').val());
$(this).siblings('.sum').val(num1 + num2);
}
});
Check Demo Here

Submitting an api request dynamically with user input

I am trying to submit a search request to the Wikipedia API using a form that is fulled out by the user. When the form is submitted, however, the page refreshes and nothing is done. I have tried to "preventDefault", and that did not get the job done. I will post my html and javascript code below (if my css is somehow helpful, I can of course supply that as well).
HTML:
<body>
<div class="random text-center">
<a target="_blank" href ="http://en.wikipedia.org/wiki/Special:Random">Get a Random Entry</a>
</div>
<br/>
<div class="text-center">
<form>
<input type="text" placeholder="search" id="search">
<input type="submit">
</form>
</div>
<div class="results">
</div>
</body>
Javascript:
$(document).ready(function(){
$('#search').submit(search());
function search(){
var value = ("#search").val();
//var value = "eggs";
$.getJSON("https://en.wikipedia.org/w/api.php?action=query&list=search&srsearch=" + value + "&utf8=&format=json&callback=?", function(json) {
json.query.search.forEach( function(val) {
var title = val.title;
var snippet = val.snippet;
titleURL = title.replace(/ /g, "_");
$(".results").append("<a target='_blank' href='https://en.wikipedia.org/wiki/" + titleURL +"'><div class='result'><div class='title'>" + title + "</div><br/><div class='snippet'>" + snippet + "</div></div></a><br/>")
});
var title = json.query.search[0].title;
var snippet = json.query.search[0].snippet;
});
};
});
codepen:
http://codepen.io/blarmon/pen/rrZzyB

Issues with converting label to input field on button click

I have modified the answer in the post dicussed here.
In my application I have two buttons - edit and save. When clicked on edit, the labels get converted into input fields, where the user can edit the content and save.
Everything is working fine, but the problem is that when the user clicks on the edit button twice, the content in the input fields becomes blank, i.e. the <input> value becomes blank.
Please suggest me a fix for this. Where am I going wrong?
<div id="companyName">
<label class="text-cname"><b>#Html.DisplayFor(m => m.Company)</b></label>
</div>
<div class="row center-block">
<input type="submit" class="btn btn-success" value="Save" id="btnSave" />
<input type="button" id="edit" class="btn btn-primary" value="Edit" />
</div>
<script>
$(document).ready(function () {
$('#edit').click(function () {
// for company name
var companyName = $('.text-cname').text();
var lblCName = $('<input id="attrCName" type="text" value="' + companyName + '" />')
$('.text-cname').text('').append(lblCName);
lblCName.select();
});
$('#btnSave').click(function () {
var text = $('#attrCName').val();
$('#attrCName').parent().text(text);
$('#attrCName').remove();
});
});
</script>
You can use replaceWith() method to convert label to textarea.
$("#edit").click(function(){
var text = $("label").text();
$("label").replaceWith("<input value='"+text+"' />");
});
$("#save").click(function(){
var text = $("input ").val();
$("input ").replaceWith("<label>"+text+"</label>");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="edit">Edit</button>
<button id="save">Save</button>
<br/><br/>
<label>Text</label>
The most simple fix would be to disable the edit button once you've clicked it, and enable it again after saving:
$(document).ready(function () {
$('#edit').click(function () {
$(this).prop('disabled', true);
/*for company name*/
var companyName = $('.text-cname').text();
var lblCName = $('<input id="attrCName" type="text" value="' + companyName + '" />')
$('.text-cname').text('').append(lblCName);
lblCName.select();
});
$('#btnSave').click(function () {
$('#edit').prop('disabled', false);
var text = $('#attrCName').val();
$('#attrCName').parent().text(text);
$('#attrCName').remove();
});
});
When you click the second time the value of companyName is empty, that's why the <input> value becomes blank. This is a very simple solution, but you lose the focus on edit box which is easy to fix.
$('#edit').click(function () {
/*for company name*/
var companyName = $('.text-cname').text();
var lblCName = $('<input id="attrCName" type="text" value="' + companyName + '" />');
if(companyName != "")
$('.text-cname').text('').append(lblCName);
lblCName.select();
});
Try This one
function EditContent(){
var companyName = $('.text-cname').text();
var lblCName = $('<input id="attrCName" type="text" value="' + companyName + '" />');
if (companyName != "") {
$('.text-cname').text('').append(lblCName);
}
lblCName.select();
}
function SaveContent(){
var text = $('#attrCName').val();
$('#attrCName').parent().text(text);
$('#attrCName').remove();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="companyName">
<label class="text-cname"><b>Company</b></label>
</div>
<div class="row center-block">
<input type="submit" class="btn btn-success" value="Save" id="btnSave" onclick="SaveContent()" />
<input type="button" id="edit" class="btn btn-primary" value="Edit" onclick="EditContent()" />
</div>

Categories