creating tooltip for dynamically created buttons - javascript

can anyone tell how to add tooltip for dynamically created button.In my page i have one submit button,and it will create dynamic buttons with respect to the xml data.i want to create tooltip for this buttons.here is my code
<script>
$(document).ready(function () {
$("#Submit").click(function () {
$.ajax({
type: "GET",
url: "mars.xml",
dataType: "xml",
success: function (xml) {
$(xml).find('student').each(function () {
var Name = $(this).find('name').text();
var Mark = $(this).find('marks').text();
var Sid = $(this).find('id').text();
var student_id = "#"+$(this).attr("id");
$("#content").append("<li><input type='button' class='dyna_btn' id = '"+$(this).attr("id")+"' value='"+Name+"'/></li>");
var hue = '#'+(0x1000000+(Math.random())*0xffffff).toString(16).substr(1,6);
$(student_id).css('color', hue);
$("#content").append('<li>' + Sid + '<li>');
});
}
});
});
});
$(document).on("click", ".dyna_btn", function() {
alert("button"+$(this).attr("id"));
console.log("button clicked");
});
</script>
<body>
<form id="From1" method="post">
<input type="button" value="submit" name="Submit" id="Submit" />
<div id="content">
</div>
</form>
</body>

Just add title="" attribute in same way like this:
<input type='button' class='dyna_btn' id = '"+$(this).attr("id")+"' value='"+Name+"' title='"+Name+"' />

Related

How to send POST requests from dynamic fields?

I'm creating a quiz form to pass into a JSON file, but I'm having trouble sending the POST requests. I'm not sure which fields I can access, or how.
This is the form: https://i.imgur.com/6xtmt3a.png
<script>
// input field
$(document).ready(function() {
var wrapper = $(".div1");
var newbutton = $(".add_form_field");
var fields = 1;
$(newbutton).click(function(e) {
e.preventDefault();
$(wrapper).append(' <div class="input-group"> <input type="text" value = "Question" class="form-control" placeholder="Recipients username" <div class="input-group-append" id="button-addon4"><button class="btn btn-outline-secondary" id ="delete" type="button">Delete</button><button class="btn btn-outline-secondary" id ="add" type="button">Add</button></div></div></div>'); //add input box
//$(wrapper).append('<button type="button" id ="test1" class="btn btn-primary">Primary</button>'); //add input box
//$(wrapper).append('<div><input type="text" value = "Question"name="mytext[]"/> Delete add </div> '); //add input box
var d = $(this).parent('form').serialize();
console.log(d);
});
//delete buttons
$(wrapper).on("click", "#delete", function(e) {
e.preventDefault();
$(this).parent('div').remove();
fields--;
})
// remove div
$(wrapper).on("click", '#s1', function(e) {
//$(this).parent('div').parent('div').remove();
var q= $(this).parent().serialize();
console.log(q);
})
//add answer
$(wrapper).on("click", "#add", function(e) {
e.preventDefault();
$(this).parent('div').append('\n <div class="input-group flex-nowrap"><div class="input-group-prepend"><span class="input-group-text" id="addon-wrapping">-</span></div><input type="text" class="form-control" placeholder="Answer" aria-label="Username" aria-describedby="addon-wrapping"></div> ' );
var d = $(this).parent('form').serialize();
console.log(d);
//$(this).parent('div').parent('div').append('<div class="input-group mb-3"><input type="text" class="form-control" placeholder="Recipients username" aria-label="Recipients username" aria-describedby="button-addon2"><div class="input-group-append"><button class="btn btn-outline-secondary" type="button" id="button-addon2">Button</button></div></div>' );
fields--;
})
});
$( "#quizForm" ).submit(function( event ) {
var $form = $( this ),
path = $form.attr( "action" );
payload = {"testKey":"test"};
var posting = $.ajax({
url: path,
method: "POST",
headers: {'X-CSRFToken': '{{ csrf_token }}'},
data: payload,
dataType: "application-json",
});
console.log(payload);
posting.done(function() {
console.log("posted");
});
});
</script>
I need to have a JSON file output on submit that contains the questions and answers to each question (right or wrong for now) Thanks!
I would suggest adding an attribute contains the object's key on each question - let's say it will be the "question ID".
we will have something like that:
<div class="question-container" question-id="01"></div>
Assuming that answers are an .answer div with an input inside we will have something like that on form submit:
let formObject = new Object();
$('.question-container')
.each(function () {
const questionID = this.attr('question-id');
const answersArray = new Array();
this.find('.answer input')
.each(function () { // assuming answer is a div contains an input tag
answersArray.push(this.value());
})
formObject[questionID] = answersArray;
})
/// here formObject contains the formatted form as json

Submitting 2 forms separately via AJAX - Python Flask

I'm trying to submit 2 separate forms via AJAX, but on submitting form2 I get a 500 bad request error.
My HTML code is below, but basically my page is a flask template that works as follows:
*User makes selections
*These selections are then posted via the submit button named "button" Value "Calculate Available Overall Heights".
*This runs some SQL query to determine a list of entries that are placed into a newly generated <select id="mySelect" class="form-control" onchange="myFunction()"></select>
This is done by JS which is also listed below as MyJS.js
OAH.html
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<p class="h2">XXX</p>
<form method="post" id="form1">
<fieldset>
</div>
<div class="col-sm-3">
<span style="float:left"><label>Overall Height</label></span>
///my inputs, various selects etc ///
<div id="response">
<!-- Empty element until form submitted-->
</div>
<p id="ApertureHeight"></p>
<p id="ApertureHeightBelowPelmet"></p>
<p id="ApertureHeightUnderRoofSticks"></p><br>
<p id="OverallWidth"></p>
<p id="RearAppWidth"></p>
<p id="RearPillarNS"></p>
<p id="OAH"></p>
</div>
</fieldset>
<script src="/static/js/MyJS.js"></script>
</form>
<form method="post" id="form2">
<div class="col-sm-3">
<label>
<span style="float:left"><input type="text" id="myText" value=""></span>
</label>
<br>
<input type="button" value="Click Me!" onclick="submitForms()" />
</div>
</form>
</body>
</html>
form2 has a button called "Click Me!" which calls a function that submits form 2.
submitForms = function(){
document.getElementById("form2").submit();
};
MyJS.js
$("#form1").on("submit", function(event) {
$targetElement = $('#response');
event.preventDefault();
// Perform ajax call
//
console.log("Sending data: " + $(this).serialize());
$.ajax({
url: '/OAH',
data: $('form').serialize(),
datatype: 'json',
type: 'POST',
success: function(response) {
// Success handler
var TableTing = response["table"];
$("#TableThing").empty();
$("#TableThing").append(TableTing);
for (key in response) {
if (key == 'myList') {
// Add the new elements from 'myList' to the form
$targetElement.empty();
select = $('<select id="mySelect" class="form-control" onchange="myFunction()"></select>');
response[key].forEach(function(item) {
select.append($('<option>').text(item));
});
$targetElement.html(select);
} else {
// Update existing controls to those of the response.
$(':input[name="' + key + '"]').val(response[key]);
}
}
return myFunction()
// End handler
}
// Proceed with normal submission or new ajax call
})
});
submitForms = function(){
document.getElementById("form2").submit();
};
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
$("#form2").on("submit", function(event) {
event.preventDefault();
console.log("Sending data: " + $(this).serialize());
$.ajax({
url: '/OAH',
data: $('#form2').serialize(),
datatype: 'json',
type: 'POST',
success: function(response) {
return myFunction()
// End handler
}
// Proceed with normal submission or new ajax call
})
});
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
function myFunction() {
var FifthWheel = document.getElementById("FifthWheelHeight").value;
var NeckDepth = document.getElementById("NeckDepth").value;
var CantRailDepth = document.getElementById("CantRailDepth").value;
var RearTensioner = document.getElementById("RearTensioner").value;
var OAH = document.getElementById("mySelect").value;
if (CantRailDepth = 115) {
var PelmetDim = 100;
} else {
PelmetDim = 75;
}
var ApertureHeight = Number(OAH) - Number(FifthWheel) - Number(NeckDepth) - Number(CantRailDepth);
var ApertureHeightBelowPelment = Number(ApertureHeight) - Number(PelmetDim);
var ApertureHeightUnderRoofSticks = Number(OAH) - Number(FifthWheel) - Number(NeckDepth) - 35;
document.getElementById("ApertureHeight").innerHTML = "Aperture below Cantrail = " + ApertureHeight + "mm";
document.getElementById("ApertureHeightBelowPelmet").innerHTML = "Aperture below pelmet = " +
ApertureHeightBelowPelment + "mm";
document.getElementById("ApertureHeightUnderRoofSticks").innerHTML = "Aperture below roof sticks = " +
ApertureHeightUnderRoofSticks + "mm";
document.getElementById("OverallWidth").innerHTML = "Overall Width = 2548mm (2550mm on spec)";
document.getElementById("OAH").innerHTML = OAH;
document.getElementById("myText").value = document.getElementById("OAH").innerHTML;
}
I need this form to submit separately, via AJAX without refreshing the page, as I need the JSON array to be able to calculate further stuff that will be passed into Python Flask. My issue is I am getting a bad request when submitting form2.
Anyone got any ideas on what I have done wrong?
I think you are using the same endpoint URL to try handle 2 different requests. The 2nd form does not send the correct data and you're then getting Server errors. Try creating another endpoint on your python flask server for handling form2 and the myText field value.

Pressing enter to search not working?

I'm trying to build a wikipedia viewer using Wikipedia's API, but I have a minor problem. If I manually press the search button, everything works fine, but if I press enter, nothing happens. Here's the js code:
$(document).ready(function () {
$("#input").keyup(function (event) {
if (event.keyCode == 13) {
$("#submit-button").click();
}
});
});
function wikiSearch() {
var query = document.getElementById("input").value;
var wiki_api = 'https://en.wikipedia.org/w/api.php';
var api = "https://en.wikipedia.org/w/api.php?action=query&prop=extracts&exlimit=max&format=json&exsentences=1&exintro=&explaintext=&generator=search&gsrlimit=10&gsrsearch=";
var wikilink = 'http://en.wikipedia.org/?curid=';
var link = api + query;
var html = "";
$.ajax({
url: link,
type: "get",
dataType: "JSONP",
success: function (data) {
var results = data.query.pages;
var pgs = Object.keys(results);
pgs.forEach(function (page) {
var title = results[page].title;
var text = results[page].extract;
var pagelink = wikilink + results[page].pageid;
html += '' + '<div class="item">' + title + '<br>' + '<p class="description-text" >' + text + '</p>' + '</div> <br> ';
});
$('#display').html(html);
}
});
}
And here's the html code:
<div class="container" id="content">
<h1>Wikipedia Viewer</h1>
<form>
<input type="text" name="search" placeholder="Search Wikipedia" id="input">
</form>
Random page
<input id="submit-button" type="button" value="Search" onclick="wikiSearch()" class="btn btn-success">
<div id="display"></div>
</div>
Here's a jsfiddle: https://jsfiddle.net/tbgoy836/
Replace input type="button" to submit. Also the input type="submit" should be inside the form. In that case you don't need to check the keycode & preventDefault will prevent the default behaviour of the form submit, since form is getting submitted using ajax. On pressing enter/return it will find the first submit button by itself and will trigger a click action
$(document).ready(function() {
$("#searchForm").submit(function(e) {
e.preventDefault();
wikiSearch()
})
});
function wikiSearch() {
console.log('wikiSearch')
var query = document.getElementById("input").value;
var wiki_api = 'https://en.wikipedia.org/w/api.php';
var api = "https://en.wikipedia.org/w/api.php?action=query&prop=extracts&exlimit=max&format=json&exsentences=1&exintro=&explaintext=&generator=search&gsrlimit=10&gsrsearch=";
var wikilink = 'http://en.wikipedia.org/?curid=';
var link = api + query;
var html = "";
$.ajax({
url: link,
type: "get",
dataType: "JSONP",
success: function(data) {
var results = data.query.pages;
var pgs = Object.keys(results);
pgs.forEach(function(page) {
var title = results[page].title;
var text = results[page].extract;
var pagelink = wikilink + results[page].pageid;
html += '' + '<div class="item">' + title + '<br>' + '<p class="description-text" >' + text + '</p>' + '</div> <br> ';
});
$('#display').append(html);
}
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container" id="content">
<h1>Wikipedia Viewer</h1>
<form id="searchForm">
<input type="text" name="search" placeholder="Search Wikipedia" id="input">
<div>
Random page
<input id="submit-button" type="submit" value="Search" onclick="wikiSearch()" class="btn btn-success">
</div>
</form>
<div id="display"></div>
</div>
Why you don't call function in javascript?
$("#submit-button").click(function(){
wikiSearch();
})
And remove onclick parameter of input.
Try $("#submit-button").trigger("click");
Or
you can simply call the function wikiSearch() instead of trigger the click event of submit button

User input does not get captured/stored

I am trying to figure out why this onclick function in my JavaScript and Jquery code are not working.
I am referring my "userInput" in the JavaScript code and storing it in a variable called "userDate". For some reason, the user input does not get captured/stored.
This is my HTML:
<form role="form">
<p> Enter the date:
<input id="userInput" type="text" placeholder="yyyy-mm-dd" autofocus required></p>
<button id="convert" type="submit" class="btn btn-primary btn-lg" padding="center">
<span class="glyphicon glyphicon-euro"></span>
</button>
</form>
This is my JS code:
$(function () {
// cache the DOM element
var $currencies = $("#currencies");
var $userInput = $("#userInput");
// We are listening on the 'document',
// for a click on an element with an ID of #convert in the HTML
$("#convert").on("click", function() {
var userDate = $userInput;
// testing
console.log(userDate);
alert ("Handler for .click() is called.");
// AJAX call for GET request
$.ajax({
type: 'GET',
url: 'http://xxx.xx',
success: function(currencies) {
console.log("success func is called");
console.log(userDate);
$.each(currencies, function(i, currency){
$currencies.append("<div> EUR: " + currencies.rates["EUR"] + ", date: " + currencies.date + "</div>");
});
},
// error handling for my request
error: function() {
alert("error loading currencies");
}
});
});
});
change
var userDate = $userInput;
to
var userDate = $userInput.val();
$userInput is a reference to the jquery object holding the input element. Using .val() returns the text value of that input element.

grails button to do ajax call to change textbox

I have a method in my controller
def returnJames = {
JSONObject jsonObject = new JSONObject()
jsonObject.put("name","James")
return jsonObject
}
and then I have a view:
<html>
<!--import gsp that has all the jquery imports-->
<script>
function changeName()
{
$.ajax({
url:"<g:createLink url="[action:'returnJames',controller:'mycontroller']" />",
dataType: "json",
asnyc: false,
success: function(data) {
$('mytextbox').val(it.name)
}
});
}
</script>
<g:form controller="mycontroller" method="post" >
<g:textField name="mytextbox" value="" />
<button name = "mybutton" id = "mybutton" onclick="changeName()">change name</button>
</g:form>
</html>
However it just tries to change the page to the index view of the mycontroller controller which doesn't exist. How can I get it to just fill in the textbox with "James"?
User render instead of return
render jsonObject
and change in jQuery
success: function(data) {
$('#mytextbox').val(data.name)
}
change button to
<input type="button" id = "mybutton" onclick="changeName()" value="change name"/>

Categories