I have multiple forms on the page, they are generated with Jinja2 and Flask, each form has it's own unique id, there is a button in each form. I want to click the button and get the values of the form where the button is actually located. However, when I try to serialize the form, it is empty. All the console.log lines work fine, each button does indeed retrieve the form it is located in.
HTML:
<form id='{{ "item-"+item.articleNr }}' class="itemTemplate">
<div class="thumb">
<img style="width: 200px;height: 200px;" src="{{ url_for('static',filename='images/'+item.image) }}">
</div>
<div class="contentWrapper">
<div class="content" id="item-content">
<label id="articleNameBlock" name="articleName">{{ item.articleName }}</label>
<div class="articleNrBlock" name="articleNr">{{ item.articleNr }}</div>
<div class="eanBlock" name="ean">{{ item.ean }}</div>
<div class="articleCodeBlock" name="articleCode">{{ item.articleCode }}</div>
<div class="articleColorBlock" name="color">{{ item.Color }}</div>
<div class="priceBlock" name="price">{{ item.Price }}</div>
<div class="buttons">
<button id="addLabel" class="ui-btn ui-btn-inline btn btn-success" type="submit">Label Aanvragen</button>
</div>
</div>
</div>
</form>
JS:
$(document).ready(function(){
$('.btn-success').on('click',function(){
console.log('The addButton is clicked.');
var $form = $(this).parents('form');
var data = $form.serialize();
console.log('Form '+ $form.attr('id'));
console.log(data)
});
//when the form is submitted
$('form').submit(function (evt) {
evt.preventDefault(); //prevents the default action
});
})
I solved my problem, thanks to the hint given by CBroe, I was indeed having a wrong approach. I changed the code. Here is the solution:
HTML:
<div id='{{ "item-"+item.articleNr }}' class="itemTemplate">
<div class="thumb">
<img style="width: 200px;height: 200px;" src="{{ url_for('static',filename='images/'+item.image) }}">
</div>
<div class="contentWrapper">
<div class="content" class="itemContent">
<label class="articleNameBlock" name="articleName">{{ item.articleName }}</label>
<div class="articleNrBlock" name="articleNr">{{ item.articleNr }}</div>
<div class="eanBlock" name="ean">{{ item.ean }}</div>
<div class="articleCodeBlock" name="articleCode">{{ item.articleCode }}</div>
<div class="articleColorBlock" name="color">{{ item.Color }}</div>
<div class="priceBlock" name="price">{{ item.Price }}</div>
<div class="buttons">
<button class="ui-btn ui-btn-inline btn btn-success" type="submit">Label Aanvragen</button>
</div>
</div>
</div>
</div>
JS:
$('.btn-success').on('click',function(){
console.log('The addButton is clicked.');
var $item = $(this).closest('.itemContent');
var $elements = $item.children();
var x = $item.children('.articleNameBlock')[0].innerHTML;
var articleName = $elements[0].innerHTML;
});
Firstly I would change the
var $form = $(this).parents('form');
to
var $form = $(this).closest('form');
as parents() traverses the DOM and selects all matching elements.
Secondly I'd change the
$('form').submit(function (evt)
to
$(document).on("submit", "form", function()
to make sure form elements are correctly selected.
I would also check my html if it is well-formed, a form tag inside a form tag doesn't work.
Related
again, probably a terrible title - but what I'm trying to do is to make a simple search feature on my website. You click a nav button, which updates the search bar, whi in turn triggers an onchange event to update the current appended list.
function update() {
var list = $("#comic__modern-list");
list.empty();
$.each(Object.keys(comics), function() {
var currentObject = comics[this];
var filter = comics[this].type;
var publisher = comics[this].publisher;
if (search == "") {
if(filter == "modern") {
list.append(`
<div class="comic__box">
<div class="comic__image-box">
<img src="${currentObject['data-item-image']}" alt="${currentObject['data-item-description']}" class="img-fluid">
<div class="comic__desc-wrap">
<div class="comic__desc">${currentObject['data-item-description']}, issue #${currentObject['issue']} (${currentObject['year']})</div>
</div>
</div>
<div style="text-align:center; margin-top: 1rem">
<button
class="btn btn-warning snipcart-add-item comic__button"
data-item-id="${currentObject['data-item-id']}"
data-item-price="${currentObject['data-item-price']}"
data-item-url="${currentObject['data-item-url']}"
data-item-description="${currentObject['data-item-description']}"
data-item-image="${currentObject['data-item-image']}"
data-item-name="${currentObject['data-item-name']}">
<div class="comic__desc-desk">£${currentObject['data-item-price']}<br>Add to cart</div><div class="comic__desc-mob">BUY <br> ${currentObject['data-item-description']}, Issue: ${currentObject['issue']} (${currentObject['year']})</div>
</button>
</div>
</div>
`)
}
} else if (search == publisher) {
list.append(`
<div class="comic__box">
<div class="comic__image-box">
<img src="${currentObject['data-item-image']}" alt="${currentObject['data-item-description']}" class="img-fluid">
<div class="comic__desc-wrap">
<div class="comic__desc">${currentObject['data-item-description']}, issue #${currentObject['issue']} (${currentObject['year']})</div>
</div>
</div>
<div style="text-align:center; margin-top: 1rem">
<button
class="btn btn-warning snipcart-add-item comic__button"
data-item-id="${currentObject['data-item-id']}"
data-item-price="${currentObject['data-item-price']}"
data-item-url="${currentObject['data-item-url']}"
data-item-description="${currentObject['data-item-description']}"
data-item-image="${currentObject['data-item-image']}"
data-item-name="${currentObject['data-item-name']}">
<div class="comic__desc-desk">£${currentObject['data-item-price']}<br>Add to cart</div><div class="comic__desc-mob">BUY <br> ${currentObject['data-item-description']}, Issue: ${currentObject['issue']} (${currentObject['year']})</div>
</button>
</div>
</div>
`)
}
});
}
The current list is generated by this, which works fine:
$.each(Object.keys(comics), function() {
var currentObject = comics[this];
var currentObject2 = comics[this].type;
console.log(currentObject2);
if (search == "") {
if(currentObject2 == "modern") {
var list = $("#comic__modern-list");
list.append(`
<div class="comic__box">
<div class="comic__image-box">
<img src="${currentObject['data-item-image']}" alt="${currentObject['data-item-description']}" class="img-fluid">
<div class="comic__desc-wrap">
<div class="comic__desc">${currentObject['data-item-description']}, issue #${currentObject['issue']} (${currentObject['year']})</div>
</div>
</div>
<div style="text-align:center; margin-top: 1rem">
<button
class="btn btn-warning snipcart-add-item comic__button"
data-item-id="${currentObject['data-item-id']}"
data-item-price="${currentObject['data-item-price']}"
data-item-url="${currentObject['data-item-url']}"
data-item-description="${currentObject['data-item-description']}"
data-item-image="${currentObject['data-item-image']}"
data-item-name="${currentObject['data-item-name']}">
<div class="comic__desc-desk">£${currentObject['data-item-price']}<br>Add to cart</div><div class="comic__desc-mob">BUY <br> ${currentObject['data-item-description']}, Issue: ${currentObject['issue']} (${currentObject['year']})</div>
</button>
</div>
</div>
`)
}
}
});
From what I can gather, this has to do with the keyword "this" no longer meaning what it did when it was outside of the function, so I'm assuming the fix will be to do with bind(), but I can't make heads nor tails of it.
p.s, if there's an easier/simpler way to set up a search system, please enlighten me!
JQuery noob here, I'm trying to make appear/disappear divs depending on multiple form select options.
My problem is that the div hide successfully, but I can't manage to make them appear back again when an option is selected.
Here is my JQuery code
<script type="text/javascript">
$(document).ready(function () {
$('#areaFields').hide();
$('#areaItems').hide();
$('#areaPartners').hide();
$('#hidden3').hide();
$('#items').hide();
$('#partners').hide();
$('#fields').hide();
$('#hidden2').hide();
$('#block').hide();
$('#ORDER').hide();
$('#type').change(function () {
$('#ORDER').hide();
$('#' + $(this).val()).show();
});
});
</script>
and here is my HTML
<div class="container">
<div class="content-section">
<form method="POST" action="">
{{ form.hidden_tag() }}
<fieldset class="form-group">
<legend class="border-bottom mb-4">Customizing</legend>
<div class="container">
<div class="form-group default1">
<div class="row">
<div class="col">
<div id="taille" class="form-group">
{{ form.tailleDocX.label }}
{{ form.tailleDocX }}
{{ form.tailleDocY.label }}
{{ form.tailleDocY }}
</div>
</div>
</div>
<div class="row">
<div class="col">
<div id="type" class="form-group">
{{ form.type.label }}
{{ form.type }}
</div>
</div>
<div class="col">
<div id="customer" class="form-group">
{{ form.customer.label }}
{{ form.customer }}
</div>
</div>
</div>
</div>
<div id="ORDER" class="form-group">
<hr>
<div class="row">
<div class="col">
<div id="block" class="form-group">
{{ form.block.label }}
{{ form.block }}
</div>
</div>
</div>
<div id="hidden2" class="form-group">
<hr>
<div class="row">
<div class="col">
<div id="items" class="form-group">
{{ form.itemsFields.label }}
{{ form.itemsFields }}
</div>
<div id="partners" class="form-group">
{{ form.partnersFields.label }}
{{ form.partnersFields }}
</div>
<div id="fields" class="form-group">
{{ form.fields.label }}
{{ form.fields }}
</div>
</div>
</div>
</div>
<div id="hidden3" class="form-group">
<hr>
<div class="row">
<div class="col">
<div id="areaFields" class="form-group">
{{ form.areaFields }}
</div>
<div id="areaItems" class="form-group">
{{ form.areaItems }}
</div>
<div id="areaPartners" class="form-group">
{{ form.areaPartners }}
</div>
</div>
</div>
</div>
<div class="form-group default2">
<hr>
<div class="row">
<div class="col">
{{ form.submit }}
</div>
</div>
</div>
</div>
</div>
</fieldset>
</form>
</div>
To create the form I'm using WTForm from FLASK, if needed here is the code :
class AreaFields(FlaskForm):
area1 = IntegerField("X0")
area2 = IntegerField("X1")
area3 = IntegerField("Y0")
area4 = IntegerField("Y1")
textArea = StringField("Texte")
class AreaItems(FlaskForm):
name = StringField("Name")
class AreaPartners(FlaskForm):
area1 = IntegerField("X0")
area2 = IntegerField("X1")
area3 = IntegerField("Y0")
area4 = IntegerField("Y1")
rolePartners = SelectField("Role", id="role")
class AjouterForm(FlaskForm):
type = SelectField("Type",
choices=[("INVOICE", "invoice"), ("ORDER", "order"), ("SERVICE_REQUEST", "service_request")],
id="type")
block = SelectField("Block", choices=[("ITEMS", "items"), ("PARTNERS", "partners"), ("fields", "fields")],
id="block")
itemsFields = SelectField("Champs", id="items")
partnersFields = SelectField("Champs", id="partnersFields")
fields = SelectField("Champs", id="fields")
tailleDocX = IntegerField("Taille X", validators=[DataRequired()])
tailleDocY = IntegerField("Taille Y", validators=[DataRequired()])
customer = SelectField("Customer", choices=[("NotFinalData", "NotFinalData")])
areaFields = FormField(AreaFields)
areaItems = FormField(AreaItems)
areaPartners = FormField(AreaPartners)
submit = SubmitField('Voir le résumer')
For the moment what I want is : to hide all the div like I did, then show the div #ORDER if order is selected in the form, or to hide the div again if another option is selected, then I'll do the same for the others select and div once I can manage to make it work.
Thanks for reading !
Edit 1 : My first select that manage the first hide/show is form.type, it contains 3 options : INVOICE, ORDER, SERVICE_REQUEST
When I select INVOICE or SERVICE_REQUEST, everything must stay hide because thoose option aren't ready for the moment, but when I select ORDER, I wish to make appear the divs #ORDER and #block. #ORDER contains all the other divs specific to the ORDER option, #block contain another select that will make appear/disappear another div depending on the option selected.
Here is a picture to show the actual form without being hidden
The first select is Type, it must make appear Block if order is selected, and block make appear a Champs depending on the option selected.
Edit 2 : BIG NEWS, I just found out what was my problem, it's so dumb of me for not seeing this at first, I used the same ID for the div and for the WTForm select... so basicly I was checking for changement for the div and not for the select... I just feel so dumb right now, thank you for trying to help me !
You just have to hide only the element your previously showed. your code should look like this.
<script type="text/javascript">
$(document).ready(function () {
var current_element = '';
$('#areaFields').hide();
$('#areaItems').hide();
$('#areaPartners').hide();
$('#hidden3').hide();
$('#items').hide();
$('#partners').hide();
$('#fields').hide();
$('#hidden2').hide();
$('#block').hide();
$('#ORDER').hide();
$('#type').change(function () {
var id = $(this).val()
$('#' + id).show();
// hide previously showed element
if(current_element != '') $('#' + current_element).hide();
// store id of previously selected element
current_element = id
});
});
</script>
I created a sample code to view xml data. When the page is loading, my current code load full xml file. But I need to load XML file after the button click. How can I fix the issue?
here is the code
$(document).ready(function(){
$.ajax({
type:"GET",
url:"contact.xml",
dataType:"xml",
success:showCD
});
});
function showCD(xml){
xml = $(xml).children();
$(xml).children().each(function () {
let TITLE = $(this).find("TITLE").text();
let ARTIST =$(this).find("ARTIST").text();
let COUNTRY = $(this).find("COUNTRY").text();
let COMPANY =$(this).find("COMPANY").text();
let html = `<div class="col-md-4">
<div class="thumbnail">
<p>${TITLE}</p>
<p>${ARTIST}</p>
<p>${COUNTRY}</p>
<p>${COMPANY}</p>
</div> </div>`;
$("#xmldata").append(html);
});
}
<section>
<div class="container">
<input type="button" value="View All" id="myButton1" class="reveal" style="float: right;" onclick="toggler('toggle_container');">
<div id="toggle_container" class='hide'>
<div class="block">
<div class="row" id="xmldata"></div>
</div>
</div>
</div>
</section>
Plunker
Just add a click event listener to the button and put the AJAX request inside the handler.
$(document).ready(function(){
// adding click event listener to the button
$('#myButton1').on('click', function() {
// make the AJAX request
$.ajax({
type:"GET",
url:"contact.xml",
dataType:"xml",
success:showCD
});
});
});
function showCD(xml){
xml = $(xml).children();
$("#xmldata").empty();
xml.each(function () {
let TITLE = $(this).find("TITLE").text();
let ARTIST =$(this).find("ARTIST").text();
let COUNTRY = $(this).find("COUNTRY").text();
let COMPANY =$(this).find("COMPANY").text();
let html = `<div class="col-md-4">
<div class="thumbnail">
<p>${TITLE}</p>
<p>${ARTIST}</p>
<p>${COUNTRY}</p>
<p>${COMPANY}</p>
</div> </div>`;
$("#xmldata").append(html);
});
}
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<section>
<div class="container">
<input type="button" value="View All" id="myButton1" class="reveal" style="float: right;" onclick="toggler('toggle_container');">
<div id="toggle_container" class='hide'>
<div class="block">
<div class="row" id="xmldata"></div>
</div>
</div>
</div>
</section>
I ask a question about my function Javascript.
I recover a data list after an a ajax call.
In the list i have a field with a picture and i want show this in a modal bootstrap.
In my code the picture is displayed below the column.
Thanks in advance guys :)
$.when(promiseListeRubriqueDocument).then(function(result) {
var data = JSON.parse(result);
$(".listRubrique").html("");
$.each(data, function(index, item) {
console.log(item);
var rubTemplate = $(".template");
var modal = (".img");
var rub = $(rubTemplate).clone().removeClass("template").removeClass("hide");
$(rub).find(".labelRubrique").text(item.codeRubrique);
$(rub).find(".inputRubrique").val(item.libelleRubrique);
$(rub).find("div.rubrique-image").attr("data-rubrique-id", item.idRub);
$(rub).find("div.rubrique-image[data-rubrique-id=" + item.idRub + "]").click(function(i, element) {
if (item.imageRubrique) {
if ($("" + "[data-rubrique-id=" + item.idRub + "]").find('img.rubrique-exemple').length < 1) {
$("" + "[data-rubrique-id=" + item.idRub + "]").append("<div><img class='rubrique-exemple' src=" + item.imageRubrique + " width='100px' /></div>");
}
}
});
$(".listRubrique").append(rub);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<li class="list-group-item template hide">
<label class="labelRubrique" style="font-weight:bold"></label>
<div class="row rubrique-image" data-rubrique-id="">
<div class="col-md-8">
<input name="enteteRubrique" id="enteteRubrique" maxlength="255" type="text" class="form-control aveo-icon aveo-magnifier inputRubrique" disabled/>
</div>
<div class="col-md-3">
<a class="seeImage" href="javascript:void(0);" role='button' aria-expanded='false' aria-controls='collapseExample'><span class='glyphicon glyphicon-eye-open fa-lg'></span></a>
</div>
</div>
</li>
<div class="row">
<div class="col-md-4">
<div class="panel panel-default">
<div class="panel-heading">
<liferay-ui: messagekey="admin.gestion.documents.rubriques.disponibles" />
</div>
<div class="panel-body">
<ul class="list-group listRubrique">
</ul>
</div>
</div>
</div>
</div>
"Lightbox" is the common name for what you've described. Since you mentioned a modal bootstrap, something like http://jbutz.github.io/bootstrap-lightbox/ is likely to be aligned with your goals.
simply clone your "field" div, give it id then append to a bootstrap modal body. Or to avoid appending new clone everytime: use .html() instead.
from https://www.w3schools.com/bootstrap/bootstrap_modal.asp with modification, using bootstrap 3.3.7, jquery 3.3.1
<body>
<div class="container">
<button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal">Open Modal</button>
<div id='myColumn'>
<img src="https://via.placeholder.com/350x150"/>
<p>Some text in the modal.</p>
</div>
</div>
<script>
$(document).ready(function(){
// var field = $("" + "[data-rubrique-id=" + item.idRub + "]").clone();
var fieldtest= $('#myColumn').clone();
var modal = $("<div id='myModal' class='modal'>\
<div class='modal-dialog'>\
<div class='modal-content'>\
<div id='myBody' class='modal-body'>\
</div>\
</div>\
</div>\
</div>").appendTo('body');
// $('#myBody').html(field);
$('#myBody').html(fieldtest);
});
</script>
</body>
`
<div class="lsiting-main">
<div class="row">
<div class="col-md-8">
<div class="col-md-4 text-right">
<span class="close-list">
<span class="funded-list">
<span class="new-list">
<div class="technology closedlanguage" headerindex="0h">
<span class="accordprefix"> </span>
View Detail Notice
<span class="accordsuffix"></span>
</div>
</div>
</div>
<div class="thelanguage" contentindex="0c" style="display: none;">
<div align="center">
<div class="big-listing-details">
</div>
<hr>
</div>
<div class="lsiting-main">
......
</div>
<div class="lsiting-main">
......
</div>
I have list of class="listing-main" and i try to open block class="thelanguage" style="display: none;" on click of class="technology closedlanguage".
But what i need, when i click on class="technology closedlanguage" at that time class change "closedlanguage" to "openlanguage" and style change 'none' to 'block'.
But when i click, only one block open at that time from list of div's
<script type="text/javascript">
$(document).ready(function () {
$('.lsiting-main .closedlanguage').click(function (event) {
event.preventDefault();
var target = $('.thelanguage');
$(target).toggleClass('hidden show');
$('.thelanguage').css('display', 'block');
})
});
I have updated the HTML a bit and also if your willing to use JavaScript then refer the below code, it is working as per your expectation.
Here is the JSFiddle Link: Working JS Fiddle Link
JS Code is :
<script>
document.getElementById("technologyclosedlanguage").addEventListener("click", myFunction);
function myFunction(){
var thelanguage = document.getElementById("thelanguage");
var technology = document.getElementById("technologyclosedlanguage");
thelanguage.style.display="block";
technology.className = "technologyopenlanguage";
alert(technology.className); //class name changed.
}
</script>
HTML Code is :
<div class="lsiting-main">
<div class="row">
<div class="col-md-8">
<div class="col-md-4 text-right">
<span class="close-list">
<span class="funded-list">
<span class="new-list">
<div class="technologyclosedlanguage" id="technologyclosedlanguage" headerindex="0h">
<span class="accordprefix"> </span>
View Detail Notice
<span class="accordsuffix"></span>
</div>
</div>
</div>
<div class="thelanguage" id="thelanguage" contentindex="0c" style="display: none;">
<div align="center">
<div class="big-listing-details">
The Language
</div>
<hr>
</div>
<div class="lsiting-main">
......
</div>
<div class="lsiting-main">
......
</div>
Let me know if it works, and helps you. Happy Coding.
Change your script to:
<script type="text/javascript">
$(document).ready(function () {
$(".closedlanguage").click(function (event) {
var target = $(".thelanguage");
$(target).toggleClass("hidden");
$(".hidden").css("display", "none");
event.preventDefault();
});