Here I am practicing using jQuery with my html. I have a form that is asking questions about your car. The problem is everything works but after it does the form reset it deletes everything that was just added.
I debugged the program and it is doing exactly what I want but once it stops executing "writeHtml" everything it just did gets cleared.
<!DOCTYPE HTML>
<html>
<head>
<title> Sabio Practice </title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
function writeHtml(){
var model = $("#Model").val();
var make = $("#Make").val();
var year = $("#Year").val();
var vin = $("#VIN").val();
$("#pp").html("<ul>")
$("#pp").html("<li>Make: " + make + "</li>" +
"<br/><li>Model: " + model + "</li>" +
"<br/><li>Year: " + year + "</li>" +
"<br/><li>VIN: " + vin + "</li>");
$("#pp").html("</ul>")
}
console.log("got here");
$("#Register").click(function(){
writeHtml();
$("#myForm")[0].reset();
});
});
</script>
</head>
<body>
<div>
<form id = "myForm" method = "get">
<input id = "Model" placeholder = "Model"><br>
<input id = "Make" placeholder = "Make"><br>
<input id = "Year" type = "number" placeholder = "Year"><br>
<input id = "VIN" placeholder = "VIN"><br>
<button id = "Register" name = "Register"> Register</button>
<button id = "Cancel" name = "Cancel">Cancel</button>
</form>
<p id = "pp">
</p>
</div>
</body>
</html>
I just want the edits made to the DOM to be permanent.
You override with html() your content, better is to use append()
$("#pp").append("<ul>")
$("#pp").append("<li>Make: " + make + "</li>" +
"<br/><li>Model: " + model + "</li>" +
"<br/><li>Year: " + year + "</li>" +
"<br/><li>VIN: " + vin + "</li>");
$("#pp").append("</ul>")
And set the type of your button to button. Otherwise the form is submitted.
<button type="button"></button>
You should also prevent the default behavior, your event subscription should look like this:
$("#Register").click(function(e) {
e.preventDefault();
writeHtml();
$("#myForm")[0].reset();
});
when you don't set the type in a form, it's a submit;
so you should set the button type button;like this:
<button id = "Register" name = "Register" type="button"> Register</button>
So I had two problems. One was I was overwriting my innerhtml again after I overwrote it the first time.
The second problem was I did not specify a type for the button. The default type for button is "submit" since my form was therefore being submitted it was redirecting me to a fresh page of my page.
<!DOCTYPE HTML>
<html>
<head>
<title> Sabio Practice </title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
function writeHtml(){
var model = $("#Model").val();
var make = $("#Make").val();
var year = $("#Year").val();
var vin = $("#VIN").val();
var htmlText = "<ul>";
htmlText += `<li>Make: ${make}</li>
<br/>
<li>Model: ${model}</li>
<br/>
<li>Year: ${year}</li>
<br/>
<li>VIN: ${vin}</li>`;
htmlText += "</ul>"
$("#pp").append(htmlText);
}
console.log("got here");
$("#Register").click(function(e){
e.preventDefault();
writeHtml();
$("#myForm")[0].reset();
});
});
</script>
</head>
<body>
<div>
<form id = "myForm" >
<input id = "Model" placeholder = "Model"><br>
<input id = "Make" placeholder = "Make"><br>
<input id = "Year" type = "number" placeholder = "Year"><br>
<input id = "VIN" placeholder = "VIN"><br>
<button id = "Register" name = "Register"> Register</button>
<button id = "Cancel" name = "Cancel">Cancel</button>
</form>
<p id = "pp">
</p>
</div>
</body>
</html>
Related
I am trying to call weather API, but for some reason I could not see the results both in console and the webpage after entering a specific city
I called
<div id="results"></div>
and made sure to declare it in my script. Can someone help?
Update: When I combine them into one file, the code works. But when I separate them into two different files, it does not work. What am I missing here?
This is the script.js of the code
var cityform = document.getElementById("cityform");
// Check if the cityform variable is not null
if (cityform !== null) {
// Add a submit event listener to the form
cityform.addEventListener("submit", function(event) {
// Prevent the default form submission behavior
event.preventDefault();
// Get a reference to the input element
var cityInput = document.getElementById("thecity");
// Check if the cityInput variable is not null
if (cityInput !== null) {
// Get the input value
var city = cityInput.value;
// Make the API request using the city value
$.getJSON("https://api.openweathermap.org/data/2.5/weather?q=" + city + "&units=imperial&appid=0dcc391bac34298837f2047642794ee3", function(data){
console.log(data);
// Extract the data from the API response
var icon = "http://openweathermap.org/img/w/" + data.weather[0].icon + ".png";
var temp = Math.floor(data.main.temp) + "F";
var weather = data.weather[0].main;
// Get a reference to the element where the data will be displayed
var results = document.getElementById("results");
// Update the element with the data from the API
results.innerHTML = "<img src='" + icon + "'> <p>" + weather + "</p> <p>" + temp + "</p>";
});
}
});
}
Then here is the HTML
<head>
<meta charset="UTF-8">
<meta name ="viewport" content="width=device=width, intial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content ="is=edge">
<title>API</title>
<script src="https://code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=" crossorigin="anonymous"></script>
<script src = "script.js"></script>
</head>
<body>
<!-- HTML -->
<h1>Weather Report</h1>
<form id="cityform">
<label for="thecity">City:</label><br>
<input type="text" name="thecity" id="thecity"><br><br>
<button type="submit">Search</button>
</form>
<!-- Create an element where the data will be displayed -->
<div id="results"></div>
</body>
</html>
What could be the possible issue or if there's no issue, how can you display the result of the icon, temp and weather to the "results"
Paste the script.js linking part at the end.
It might be possible that when your scripts is ran form was not creaded thus those variables were not existing that time.
See both example, this works
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device=width, intial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="is=edge">
<title>API</title>
<script src="https://code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=" crossorigin="anonymous"></script>
</head>
<body>
<!-- HTML -->
<h1>Weather Report</h1>
<form id="cityform">
<label for="thecity">City:</label>
<br>
<input type="text" name="thecity" id="thecity">
<br>
<br>
<button type="submit">Search</button>
</form>
<!-- Create an element where the data will be displayed -->
<div id="results"></div>
<script>
var cityform = document.getElementById("cityform");
// Check if the cityform variable is not null
if (cityform !== null) {
// Add a submit event listener to the form
cityform.addEventListener("submit", function(event) {
// Prevent the default form submission behavior
event.preventDefault();
// Get a reference to the input element
var cityInput = document.getElementById("thecity");
// Check if the cityInput variable is not null
if (cityInput !== null) {
// Get the input value
var city = cityInput.value;
// Make the API request using the city value
$.getJSON("https://api.openweathermap.org/data/2.5/weather?q=" + city + "&units=imperial&appid=0dcc391bac34298837f2047642794ee3", function(data) {
console.log(data);
// Extract the data from the API response
var icon = "http://openweathermap.org/img/w/" + data.weather[0].icon + ".png";
var temp = Math.floor(data.main.temp) + "F";
var weather = data.weather[0].main;
// Get a reference to the element where the data will be displayed
var results = document.getElementById("results");
// Update the element with the data from the API
results.innerHTML = "<img src='" + icon + "'> <p>" + weather + "</p> <p>" + temp + "</p>";
});
}
});
}
</script>
</body>
</html>
But not this
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device=width, intial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="is=edge">
<title>API</title>
<script src="https://code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=" crossorigin="anonymous"></script>
<script>
var cityform = document.getElementById("cityform");
// Check if the cityform variable is not null
if (cityform !== null) {
// Add a submit event listener to the form
cityform.addEventListener("submit", function(event) {
// Prevent the default form submission behavior
event.preventDefault();
// Get a reference to the input element
var cityInput = document.getElementById("thecity");
// Check if the cityInput variable is not null
if (cityInput !== null) {
// Get the input value
var city = cityInput.value;
// Make the API request using the city value
$.getJSON("https://api.openweathermap.org/data/2.5/weather?q=" + city + "&units=imperial&appid=0dcc391bac34298837f2047642794ee3", function(data) {
console.log(data);
// Extract the data from the API response
var icon = "http://openweathermap.org/img/w/" + data.weather[0].icon + ".png";
var temp = Math.floor(data.main.temp) + "F";
var weather = data.weather[0].main;
// Get a reference to the element where the data will be displayed
var results = document.getElementById("results");
// Update the element with the data from the API
results.innerHTML = "<img src='" + icon + "'> <p>" + weather + "</p> <p>" + temp + "</p>";
});
}
});
}
</script>
</head>
<body>
<!-- HTML -->
<h1>Weather Report</h1>
<form id="cityform">
<label for="thecity">City:</label>
<br>
<input type="text" name="thecity" id="thecity">
<br>
<br>
<button type="submit">Search</button>
</form>
<!-- Create an element where the data will be displayed -->
<div id="results"></div>
</body>
</html>
If you want to check yourself then just after
var cityform = document.getElementById("cityform");
add alert(cityform)
When script linking is in head before body then we will get null in alert
But when the script is at end near closing body tag then alert will have the form element.
Hope it helps.
Comment if I am wrong somewhere.
You need to move script from head location inside of body in HTML
This code works
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device=width, intial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="is=edge">
<title>API</title>
<script src="https://code.jquery.com/jquery-2.2.4.min.js"
integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=" crossorigin="anonymous"></script>
</head>
<body>
<!-- HTML -->
<h1>Weather Report</h1>
<form id="cityform">
<label for="thecity">City:</label><br>
<input type="text" name="thecity" id="thecity"><br><br>
<button type="submit">Search</button>
</form>
<!-- Create an element where the data will be displayed -->
<div id="results"></div>
<script src="script.js"></script>
</body>
</html>
function resultSubmit(event) {
event.preventDefault();
// Get the input value
var city = cityInput.value;
// Make the API request using the city value
$.getJSON("https://api.openweathermap.org/data/2.5/weather?q=" + city + "&units=imperial&appid=0dcc391bac34298837f2047642794ee3", function (data) {
console.log(data);
// Extract the data from the API response
var icon = "http://openweathermap.org/img/w/" + data.weather[0].icon + ".png";
var temp = Math.floor(data.main.temp) + "F";
var weather = data.weather[0].main;
// Update the element with the data from the API
results.innerHTML = "<img src='" + icon + "'> <p>" + weather + "</p> <p>" + temp + "</p>";
});
}
const cityform = document.getElementById("cityform");
const cityInput = document.getElementById("thecity");
const results = document.getElementById('results')
cityform.addEventListener('submit', resultSubmit)
Result - I ran GO Live extension it in VS code
html tag and code relationship
I need to create a counter loop that begins after the user clicks the "submit" button. However, this "submit" button is already being used in another variable. The submit button needs to do two things here, at the same time, and I cannot figure out how to make that work. When the user inputs their information for their first name, last name, and middle initial, and then clicks the submit button, not only will the header change, but a counter to 125 needs to begin. Here is my code so far. What changes do I need to make sure that when the user clicks submit, the <h1> changes with their name in the greeting, and a loop begins counting from 1 to 125 with words like "hello world" after it.
example:
1)Hello World
2)Hello World
3)Hello World
etc
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=UTF-8" />
<link rel="stylesheet" type="text/css" href="fizzbuzz.css">
<title>Fizz Buzz 0</title>
<script>
function clickFunction(){
var firstName = document.getElementById("firstName").value;
var middleName= document.getElementById("middleName").value;
var lastName= document.getElementById("lastName").value;
document.getElementById("greeting").innerHTML =
"Welcome, " + firstName + " " + middleName+ " " +lastName + "!";
};
function clickFunction = ""; {
while (var i=0;i<125;i++) {
out = out + "London Kings" + "</br>";
document.getElementById("greeting").innerHTML = out;
}
}
</script>
</head>
<body>
<div id="header">
<p>
<img src="images/banner.jpg" alt="Banner" height="130" width="940" style="border:0" />
</p>
</div>
<div id="content">
<div id="feature">
<h2 id="greeting"> Welcome to London Kings Football! </h2>
<form>
First Name <input id="firstName"> </input>
Middle Initial <input id="middleName"> </input>
Last Name <input id="lastName"> </input>
</form>
<button onClick="clickFunction()",> Submit </button>
</div>
</div>
</body>
</html>
Some changes you can make to make to your current code so it runs
change the while loop to a for loop
initialize the out variable ( you are using it before it is defined
in a right hand assignmen)
So you final function is
function clickFunction() {
var firstName = document.getElementById("firstName").value;
var middleName = document.getElementById("middleName").value;
var lastName = document.getElementById("lastName").value;
var out = '';
document.getElementById("greeting").innerHTML = "Welcome, " + firstName + " " + middleName + " " + lastName + "!";
for (var i = 0; i < 125; i++) {
out = out + "London Kings" + "</br>";
document.getElementById("greeting").innerHTML = out;
}
}
Other things that could make your code better
Dont add the event listener inline, its harder to reason for your code
instead use document.querySelector("button").addEventListener("click", function(){});
move your script tag just before the closing body tag (</body>) this way the javascript code parsing will not block the rendering of the page (js runs in one thread)
dont query the DOM for each repetition of the for loop instead move the greeting query to the top of the function so you run it only once (per function call)
dont query for the DOM elements each time you run the code(better solution to 3 above, instead either move queries to the top level (those vars will be global, we dont like globals) or create a closure which will encapsulate your valiables
#4 example
var clickFunction = (function(){
var firstName = document.getElementById("firstName");
var middleName = document.getElementById("middleName");
var lastName = document.getElementById("lastName");
var greeting = document.getElementById("greeting");
var out = '';
return function(){
greeting.innerHTML = "Welcome, " + firstName + " " + middleName + " " + lastName + "!";
for (var i = 0; i < 125; i++) {
out = out + "London Kings" + "</br>";
greeting.innerHTML = out;
}
}
}())
document.querySelector("button").addEventListener("click", clickFunction)
script tag containing the above code has to be before the closing body tag
I have a textarea that will contains a code entered by user and I want to get that code and scan it with jQuery to get the value inside a custom tag called setting then add this value to an input so the user will be able to change the value inside setting tag without touching the code. I was able to get the values and add them inside the inputs but I couldn't update the code with the new values.
HTML CODE :
<div id='tab-1'>
<textarea id='template-code' cols='67' rows='27'></textarea>
<button id='submit-code'>Submit Code</button>
</div>
<div id='tab-2' class='unactive'>
<form id='settings-form' method='POST'>
<div id='result'></div>
<button id='update-code'>Update Code</button>
</form>
</div>
CSS CODE :
.unactive {
display: none
}
jQuery CODE :
$('#template-code').change(function (){
var $that = $(this),
template_code = $that.val(),
code = '',
new_data = '',
text = '',
newCode = '';
// Extract settings from the theme and add them to #result
$(document).on('click', '#submit-code', function (){
$('#tab-1').addClass('unactive');
$('#tab-2').removeClass('unactive');
$(template_code).find('setting').each(function (i){
var $this = $(this),
setting_std = $this.text(),
setting_id = $this.attr('id');
code += '<input id="'+setting_id+'" name="'+setting_id+'" type="text" value="'+setting_std+'"><br>';
});
if(code !== ''){
$('#result').html(code);
}
});
// Update old data with the new one
$(document).on('click', '#update-code', function (){
new_data = $( "#settings-form" ).serializeArray();
$.each( new_data, function( i, new_field ) {
var start_key = "id='"+new_field.name+"'>",
end_key = '</setting>',
start = template_code.indexOf(start_key),
end = template_code.indexOf(end_key);
text = template_code.substring(start + start_key.length, end);
// THE PROBLEM IS HERE
// I want the variable template_code to contains the new value not the old one so I used replace but it seems that it doesn't work
template_code.replace(text, new_field.value);
});
$('#template-code').val(template_code);
$('#tab-1').removeClass('unactive');
return false;
});
});
This is an example of the theme code that will be added inside the textarea :
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE html>
<html b:version='2' class='v2' expr:dir='data:blog.languageDirection' xmlns='http://www.w3.org/1999/xhtml' xmlns:b='http://www.google.com/2005/gml/b' xmlns:data='http://www.google.com/2005/gml/data' xmlns:expr='http://www.google.com/2005/gml/expr'>
<head>
<b:include data='blog' name='all-head-content'/>
<link href='http://fonts.googleapis.com/css?family=Open+Sans+Condensed:300,300italic,700' rel='stylesheet' type='text/css'/>
<link href='http://fonts.googleapis.com/css?family=Lora:400,400italic,700,700italic' rel='stylesheet' type='text/css'/>
<link href='https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css' rel='stylesheet'/>
<title><data:blog.pageTitle/></title>
<div id='option-panel' style='display:none!important'>
<setting id='post_thumbnail'>http://lorempixel.com/640/300/</setting>
<setting id='search_icon'>on</setting>
</div>
</head>
<body>
</body>
</html>
To understand my issue please enter to this JsFiddle and copy the code above then put it inside the textarea and click submit code, you will get two inputs the content of those inputs come from these two tags :
<setting id='post_thumbnail'>http://lorempixel.com/640/300/</setting>
<setting id='search_icon'>on</setting>
I want when the user change the value of inputs and click "update code" to change the value of setting tag inside the entire code.
Try this and see if it's what you're looking for:
HTML
<div id='tab-1'>
<textarea id='template' cols='67' rows='27'></textarea>
<button id='submit'>Submit Code</button>
</div>
<div id='tab-2'>
<form id='settings-form' method='POST'>
<div id='result'></div>
<button id='update'>Update Code</button>
</form>
</div>
JavaScript:
function wrap(data) {
var string = '';
var i, l;
string += "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\r\n";
string += "<!DOCTYPE html>\r\n";
string += "<html b:version='2' class='v2' expr:dir='data:blog.languageDirection' xmlns='http://www.w3.org/1999/xhtml' xmlns:b='http://www.google.com/2005/gml/b' xmlns:data='http://www.google.com/2005/gml/data' xmlns:expr='http://www.google.com/2005/gml/expr'>\r\n";
string += " <head>\r\n";
string += " <b:include data='blog' name='all-head-content'/>\r\n";
string += " <link href='http://fonts.googleapis.com/css?family=Open+Sans+Condensed:300,300italic,700' rel='stylesheet' type='text/css'/>\r\n";
string += " <link href='http://fonts.googleapis.com/css?family=Lora:400,400italic,700,700italic' rel='stylesheet' type='text/css'/>\r\n";
string += " <link href='https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css' rel='stylesheet'/>\r\n";
string += " <title><data:blog.pageTitle/></title>\r\n";
string += " </head>\r\n";
string += " <body>\r\n";
string += " <div id='option-panel' style='display:none!important'>\r\n";
for (i = 0, l = data.length; i < l; i++)
string += " " + data[i].toString() + "\r\n";
string += " </div>\r\n";
string += " </body>\r\n";
string += "</html>\r\n";
return string;
}
$("#submit").on('click', function() {
var virtual = document.createElement("div");
var temp = '';
virtual.innerHTML = $("#template").val();
$(virtual).find('setting').each(function(i) {
var $this = $(this),
setting_std = $this.text(),
setting_id = $this.attr('id');
temp += '<input id="' + setting_id + '" name="' + setting_id + '" type="text" value="' + setting_std + '"><br>';
});
if (temp !== '')
$('#result').html(temp);
});
$("#update").on('click', function(event) {
var temp = [];
event.preventDefault();
$("#result").find("input").each(function() {
temp.push("<setting id=\"" + this.id.toString() + "\">" + this.value.toString() + "</setting>");
});
$("#template").val(wrap(temp));
});
I believe that does what you're looking for? Even though you're using jQuery, I think you ended up making it a lot harder than it had to be. I used a virtual node to quickly/easily find and pull ONLY the setting tag from the textarea on submit (down and dirty, I suppose?).
I removed the styles and whatnot since it was interfering with rapid testing, and you'll need to apply proper sanity checking/validation against user input.
Edit: Updated answer to include a ghetto wrapping function to elucidate the concept. I would not recommend using it as is, but instead utilizing a real template, which would require work outside the scope of this question.
Most recent JSFiddle after editing: http://jsfiddle.net/zo3hh2ye/6/
Here's another version of the code. I saved the new values in an array and then replaced them with the existing values in the textarea text. Give a try and see if that solves your problem.
Script :
<script type="text/javascript">
$('#template-code').change(function () {
var $that = $(this),
template_code = $that.val(),
code = '',
new_data = '',
text = '',
newCode = '';
// Extract settings from the theme and add them to #result
$('#submit-code').click(function () {
$('#tab-1').addClass('unactive');
$('#tab-2').removeClass('unactive');
$(template_code).find('setting').each(function (i) {
var $this = $(this),
setting_std = $this.text(),
setting_id = $this.attr('id');
code += '<input id="' + setting_id + '" name="' + setting_id + '" type="text" value="' + setting_std + '"><br>';
});
if (code !== '') {
$('#result').html(code);
}
});
// Update old data with the new one
$('#update-code').click(function () {
new_data = $("#settings-form").serializeArray();
$(template_code).find('setting').each(function (i) {
template_code = template_code.replace("<setting", "").replace("id='" + $(this).attr("id") + "'>", "").replace($(this).html(), "{" + i + "}").replace("</setting>", "");
});
$.each(new_data, function (i, new_field) {
template_code = template_code.replace("{" + i + "}", "<setting id='" + new_field.name + "'>" + new_field.value + "</setting>");
});
$('#template-code').val(template_code);
$('#tab-1').removeClass('unactive');
return false;
});
});
</script>
HTML Template :
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE html>
<html b:version='2' class='v2' expr:dir='data:blog.languageDirection' xmlns='http://www.w3.org/1999/xhtml' xmlns:b='http://www.google.com/2005/gml/b' xmlns:data='http://www.google.com/2005/gml/data' xmlns:expr='http://www.google.com/2005/gml/expr'>
<head>
<b:include data='blog' name='all-head-content'/>
<link href='http://fonts.googleapis.com/css?family=Open+Sans+Condensed:300,300italic,700' rel='stylesheet' type='text/css'/>
<link href='http://fonts.googleapis.com/css?family=Lora:400,400italic,700,700italic' rel='stylesheet' type='text/css'/>
<link href='https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css' rel='stylesheet'/>
<title><data:blog.pageTitle/></title>
<div id='option-panel' style='display:none!important'>
<setting id='post_thumbnail'>text1</setting>
<setting id='search_icon'>text2</setting>
</div>
</head>
<body>
</body>
</html>
I couldn't replace the text 'on' in the template you provided, not sure if it has something to do with some reserved key word but everything else works fine.
I found this pass id to jquery modal form but seeing as I'm not too jQuery-savvy and I don't know PhP I'm not sure how I would implement this in my example.
My goal is to be able to pass the ID of a button, upon being pressed, to a form. Something like this:
<button id="dynamic_id">
<form id="time_form" action="{% url 'event' pk='button_id' %}" method="post">
# Lots of stuff
</form>
The button_id is where I'd like the button's ID to be.
I thought of something like
function getId(button_id) {
document.getElementById('time_form').action = "{" + "%" + "url " + "event" + ' pk="' + button_id + '" %" + "}"';
}
<button id="dynamic_id" onClick="getId(this.id);">
<form id="time_form" action=""> (...)
</form>
But this does not work. I get an error message
400 Bad Request: Your browser semt a request this server cannot understand
UPDATE
I'm not trying this:
function getId(button_id) {
var vk_input = document.CreateElement("input");
vk_input.name = "vk_id";
vk_input.value = button_id;
vk_input.type = "hidden";
document.getElementById("time_form").appendChild(vk_input);
}
But it does not work for some reason. What's wrong with it?
look this:
<script>
$(document).ready(function(){
$('#dynamic_id').click(function(){
var id=$(this).attr('id');
var array_ids = [];
$('.dinamics').each(function(){
//console.log('gdfg');
array_ids.push($(this).attr('id'));
});
for(var i = 0; i < array_ids.length; i++){
$('#time_form').append('<input type="hidden" name="your_button_id_'+i+'" value="'+array_ids[i]+'"/>')
}
$('#time_form').submit();
})
})
</script>
How aboout this with jquery.
<button id="dynamic_id">
<form id="time_form" action="" method="post">
</form>
<script>
$(document).ready(function(){
$('#dynamic_id').click(function(){
var id=$(this).attr('id');
$('#time_form').append('<input type="hidden" name="your_button_id" value="'+id+'"/>')
$('#time_form').submit();
})
})
</script>
Button id passed correctly to getId() but generated string does not seems valid, here is some issue with quotes. See reduced example on jsfiddle
try this:
document.getElementById('time_form').action = "{" + "%" + "url " + "event" + ' pk="' + button_id + '" ' + "%" + "}";
i recommend you to use jquery, is better an clean.
this is what you want?
<button id="dynamic_id" class="dinamics">Lots of stuff</button>
<button id="dynamic_id_1" class="dinamics">1</button>
<button id="dynamic_id_2" class="dinamics">2</button>
<button id="dynamic_id_3" class="dinamics">3</button>
<button id="dynamic_id_4" class="dinamics">3</button>
<button id="dynamic_id_5" class="dinamics">3</button>
<button id="dynamic_id_6" class="dinamics">3</button>
<button id="dynamic_id_7" class="dinamics">3</button>
<form id="time_form" action="" method="post">
</form>
<script>
$(document).ready(function(){
$('#dynamic_id').click(function(){
var array_ids = [];
$('.dinamics').each(function(){
array_ids.push($(this).attr('id'));
});
for(var i = 0; i < array_ids.length; i++){
$('#time_form').append('<input type="hidden" name="your_button_id_'+i+'" value="'+array_ids[i]+'"/>')
}
$('#time_form').submit();
})
})
</script>
I have a page which loads and then I do some JQuery upon it. When doing the line:
var div = $("<div class='modal'>").append(r);
I was trying to figure out why it was erroring out and saying there was a Hierarchy error. Maybe there is improper DOM in r? To save on the output as it is long, I will show the server side. r below does not error, but it is when appending it with the div above where the issues actually occur.
var r = $(result);
result:
"<div>
<input type='text' id ='queryInput' />
<button id = 'queryButton' runat='server' value = 'Re-Filter'>Re-Filter</button>
</div>
<div id='set'>
<select>
<!-- The options are populated by a loop in ASP.net -->
<option value = '" + Convert.ToString(record.fe_id) + "'>" + Convert.ToString(record.fe_name) + "</option>
</select>
</div>
<div>
<button id = 'buttonReturnValue' value = 'Return Selected Element'>Return Selected Element</button>
</div>"
What am I doing wrong where it thinks the above is improperly formed dom?
var text = "<div><input type='text' id ='queryInput' /><button id = 'queryButton' runat='server' value = 'Re-Filter'>Re-Filter</button></div><div id='set'><select><option value = '" + Convert.ToString(record.fe_id) + "'>" + Convert.ToString(record.fe_name) + "</option></select></div><div><button id = 'buttonReturnValue' value = 'Return Selected Element'>Return Selected Element</button></div>";
This is a workaround but works...
var d = document.createElement("div");
d.innerHTML = text;
document.getElementById('modal').appendChild(d);