I would like an image to be displayed based on what is entered inside the form. The problem is with figure_id as when displayed with console log it is a blank string even when text is submitted inside the form.
<form method="GET" id="figure_choice_form">
<label for="figure_id">Enter ID</label>
<input type="text" id="figure_id" name="figure_id">
</form>
<img id="figure_image" src="RESULT_FROM_THE_FUNCTION" alt="img">
JavaScript I have tried
<script>
function set_image_path(){
var figure_id = document.getElementById("figure_id").value
var image_path = `main/Bricklink/images/${figure_id}.png`
document.getElementById("figure_image").img.src = image_path
}
set_image_path()
</script>
The problem is here document.getElementById("figure_image").img.src, there is no img property.
So change it to document.getElementById("figure_image").src
function set_image_path() {
const figure_id = document.getElementById("figure_id");
const figure_image = document.getElementById("figure_image");
const image_path = `main/Bricklink/images/${figure_id.value}.png`;
figure_image.src = image_path;
console.log(figure_image.src);
}
//call function in submit listener
const form_figure = document.getElementById("figure_choice_form");
form_figure.addEventListener('submit', e => {
e.preventDefault();
set_image_path();
})
//call function in load page - if input has value
set_image_path();
<form method="GET" id="figure_choice_form">
<label for="figure_id">Enter ID</label>
<input type="text" id="figure_id" name="figure_id" value="image123">
<button> Submit </button>
</form>
<img id="figure_image" src="RESULT_FROM_THE_FUNCTION" alt="img">
Related
I'm working on an assignment that asks us to use Promise, and when I run the script, I am getting this error on line 37:
Uncaught TypeError: Cannot set property 'onclick' of null
I can't understand why the onclick is throwing this error, because I have used buttons before with similar functionality, and never had an issue. Code is below:
<!DOCTYPE html>
<html>
<head>
<title>Wanna See A Picture?</title>
</head>
<body>
<div class="container">
<form action"/setup" method="post" id="setup">
<h1>Enter your random image size</h1>
<p>Enter an image width and height by entering a number between 200 and 1200 in each field.</p>
<p>Click "Get Your Pic!" when ready.</p>
<div class="field">
<label for="width">Enter a width:</label>
<input type="number" id="width" name="width" />
</div>
<div class="field">
<label for="height">Enter a height:</label>
<input type="number" id="height" name="height" />
</div>
<div class="field">
<button type="submit">Get Your Pic!</button>
</div>
</form>
</div>
<div id="imgOutput"></div>
<script>
const SUBMITBTN = document.getElementById('submit');
let source = "";
SUBMITBTN.onclick = function(){
let imgWidth = document.getElementById('width');
let imgHeight = document.getElementById('height');
let source = `https://picsum.photos/${imgWidth}/${imgHeight}/?random`; //for grayscale add ?grayscale at end of url
}
let img = null;
let imgPromise = new Promise(function(resolve, reject){
img = new Image();
img.addEventListener('load', resolve(img));
img.addEventListener('error', reject('Could not load image'));
img.src = source;
});
imgPromise.then(function(fromResolve){
let node = document.getElementById('imgOutput');
node.appendChild(img);
}).catch(function(fromReject){
document.getElementById('imgOutput').innerHTML = fromReject
});
</script>
</body>
</html>
const SUBMITBTN = document.getElementById('submit')
Null was returned because you used getElementById and there are no ID assigned to the button. Try:
<button id="submit" type="submit">Get Your Pic!</button>
Note:
Hard-assigning id to the button may not be ideal if there are multiple submit buttons. Potentially look for a more descriptive name and find a query-selector that suits your needs.
Here is what is needed to do:
<input type="text" id="main" placeholder="Put URL Here">
Every time the User Presses enter (or a Button on side of screen) I need Jquery to create:
<input type="hidden" id="url_1" readonly value='<-- input value from main-->'>
<!-- user adds another to #main -->
<input type="hidden" id="url_2" readonly value='<-- input value from main-->'>
<!-- etc -->
Here is what I got So far (only using HTML)
<figure class="mb-4">
<input type="text" name="" id="" placeholder="Image URL">
<button id="addimage">Add Image</button>
<button id="uploadimage_js">Upload Image</button>
</figure>
For the Upload Image button, It submits a Image to my PHP upload image, and just returns the URL to the image
This will append the hidden inputs to the end of your <form> tag. It also keeps an array of urls in case that's useful. For this snippet, it shows the array in a div.
let urls = [], limit = 2, main, addButton, resetButton
window.addEventListener('load', () => {
main = document.querySelector('#main'),
addButton = document.querySelector('[data-url-saver]'),
resetButton = document.querySelector('[data-url-reset]');
addButton.addEventListener('click', () => saveURL())
resetButton.addEventListener('click', () => reset())
})
const saveURL = () => {
let u = main.value;
urls.push(u);
let h = `<input type="hidden" data-url-hidden id="url_${urls.length}" readonly value=${u} />`
document.querySelector('form').insertAdjacentHTML('beforeend', h);
main.value = "";
let de = document.querySelector('#debug');
de.innerHTML = urls.join(", ");
if (urls.length >= limit) {
addButton.setAttribute('disabled', 'disabled');
main.setAttribute('disabled', 'disabled');
main.setAttribute('placeholder', 'Maximum URLs accepted')
}
}
const reset = () => {
urls = [];
document.querySelectorAll('[data-url-hidden]').forEach(e => e.parentNode.removeChild(e));
addButton.removeAttribute('disabled');
main.removeAttribute('disabled');
document.querySelector('#debug').innerHTML = "";
}
<form>
<input type="text" id="main" placeholder="Put URL Here">
<button data-url-saver type='button'>enter</button>
<button data-url-reset type='button'>reset</button>
</form>
<div id='debug'></div>
Create a div for hidden urls like
<div id="urls"></div>
try in jquery
var counter = 1;
$('#main').keypress(function (e) {
if(e.which== 13){ // enter key code
var url = $('#main').val();
$('#urls').append('<input type="hidden" id="url_'+ counter +'" readonly value="' + url + '" >');
$('#main').val(''); //clearing the input
counter++;
}
});
If you want to add ascending URL and if you have the link, then you can use the function below.
function addImage(){
var link = document.querySelector('#main').value;
var all_links = document.getElementById('all_urls');
if (link.length > 0){
code = `
<input type="hidden" id="url_${all_links.children.length}" value="${link}"/>
`
all_links.innerHTML += code;
console.log(document.getElementById('all_urls'))
}
}
<figure class="mb-4">
<input type="text" id="main" placeholder="Put URL Here">
<div id="all_urls">
<!--All the links are added here-->
</div>
<button id="addimage" onclick="addImage()">Add Image</button>
<button id="uploadimage_js">Upload Image</button>
</figure>
In jQuery
// Cache some elements
const div = $('div');
const main = $('#main');
$('button').click(() => {
// Grab the value
const val = main.val();
// Create the id based on the current
// number of inputs
const id = div.find('input').length + 1;
// Append the new input
div.append(`<input readonly id="url_${id}" value="${val}" />`);
// Reset the main input
main.val('');
});
div { margin-top: 1em; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="main" />
<button>Click</button>
<div></div>
And the equivalent in vanilla JS:
// Cache some elements
const div = document.querySelector('div');
const main = document.querySelector('#main');
const button = document.querySelector('button');
button.addEventListener('click', handleClick, false)
function handleClick() {
// Create the id based on the current
// number of inputs
const id = div.querySelectorAll('input').length + 1;
const html = `<input readonly id="url_${id}" value="${main.value}" />`;
// Append the new input
div.insertAdjacentHTML('beforeend', html);
// Reset the main input
main.value = '';
};
div { margin-top: 1em; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="main" />
<button>Click</button>
<div></div>
Form1 is to add text, and Form2 should populate the same text as Form1, but convert it using the replace method. I am having trouble populating the text in Form2..
<form id="form1">
<input type="text" name="input" value="">
<button type="submit" name="submit" value="submit">Submit</button>
</header>
<div>
<label>Plain Text:</label>
<form id="form2">
<input type="text" name="input" value="" onchange="convertMarkdown()">
</div>
</div>
<script>
function convertMarkdown() {
const form = document.getElementById("form1");
const input = form.querySelector("input");
const form2 = document.getElementById("form2");
const convertedMarkdown = input.replace(/[(\*)(\>)(\#)(\[)(\))]/g, "").replace(/[(\]\()]/g, " ");
form.addEventListener('submit', (e) => {
// prevent browser default
e.preventDefault();
// contain text content
const text = input.value;
// print text content in form1
form1.textContent = text.text
});
form2.addEventListener('onchange', (e) => {
// prevent browser default
e.preventDefault();
// contain text content
const text = input.value;
// print converted text in form2
form2.textContent = input.replace(/[(\*)(\>)(\#)(\[)(\))]/g, "").replace(/[(\]\()]/g, " ");
};
</script>
This below js code will give your expected output.
const submit = document.getElementById("submit");
const input = document.getElementById("ip1");
submit.addEventListener('click', (e) => {
// prevent browser default
e.preventDefault();
const convertedMarkdown = input.value.replace(/[(\*)(\>)(\#)(\[)(\))]/g, "").replace(/[(\]\()]/g, " ");
// contain text content
const text = input.value;
// print text content in form1
document.forms["form2"]["input2"].value = convertedMarkdown;
});
<form name="form1">
<input id="ip1" type="text" name="input" value="">
<button id="submit" type="submit" name="submit" value="submit">Submit</button>
</form>
<div>
<label>Plain Text:</label>
<form name="form2">
<input type="text" name="input2" value="">
</form>
</div>
I'm trying to display a user input on a separate div, but only have it appear when a button is clicked. I think i have it set up but I'm just not sure how to display the input. can someone help me with how it can be done?
<script>
var callButt = document.getElementById("callButt");
var userinput = document.getElementById("userinput");
callButt.addEventListener("click", function(){
console.log("Call has been set");
userinput.style.display = "block";
</script>
<input id="callerIDInput" type="text" value="" >
<div id="userinput"> </div>
<button id='callButt'>CALL</button>
Set the input value to the innerHTML of the div
var callButt = document.getElementById("callButt");
var userinput = document.getElementById("userinput");
callButt.addEventListener("click", function() {
console.log("Call has been set");
userinput.innerHTML = document.getElementById('callerIDInput').value
})
<input id="callerIDInput" type="text" value="">
<div id="userinput"> </div>
<button id='callButt'>CALL</button>
Use innerHTML of the DIV to set the value.
HTML
<input id="callerIDInput" type="text" value="">
<div id="userinput"> </div>
<button id='callButt' onclick="Display()">CALL</button>
Javascript
function Display()
{
var callButt = document.getElementById("callButt");
var userinput = document.getElementById("userinput");
var callerIDInput = document.getElementById("callerIDInput");
console.log("Call has been set");
userinput.style.display = "block";
userinput.innerHTML = callerIDInput.value;
}
I am working on my first for validation, really basic.
If you leave the 'username' input blank it will turn the username input border red and also place an alert icon in the input.
I am trying to 'remove' what was added when the validation failed as soon as the user starts typing in the input that caused the error.
So the scenario is: The user leaves Username blank, clicks Submit and then the border of the Username input goes red and an error icon appears. They then go back and they add their username into the Username input after the first character they type into the Username box I want the red border and error icon to disappear.
However my attempts have failed
My Fiddle
JS
function contactForm() {
var theForm = document.forms.contact;
var errorUsername = document.getElementById('username-error');
var usernameInput = document.getElementById('username');
theForm.onsubmit = function() {
if (theForm.username.value === '') {
errorUsername.style.display = 'block';
usernameInput.className = 'form__input form__input--red rounded-4';
return false;
} else {
theForm.username.onkeydown = function() {
errorUsername.style.display = 'none';
usernameInput.className = 'form__input rounded-4';
};
return true;
};
};
};
contactForm();
HTML
<form name="contact" action="#" novalidate>
<div class="input__holder">
<input id="username" name="username" type="text" class="form__input rounded-4" placeholder="Username">
<div id="username-error" class="input__error">!</div>
</div>
<div class="input__holder">
<input name="password" type="password" class="form__input rounded-4" placeholder="Password">
</div>
<div class="input__holder">
<input name="email" type="text" class="form__input rounded-4" placeholder="E-mail">
</div>
<button type="submit" id="" class="submit-button rounded-4">Submit</button>
</form>
CSS
Too long, in Fiddle :)
You can add something like this on javascript
document.onkeyup = function() {
var errorUsername = document.getElementById('username-error');
var usernameInput = document.getElementById('username');
if (usernameInput.value.length === 0) return;
errorUsername.style.display = 'none';
usernameInput.className = 'form__input rounded-4';
}
Here the fiddle:
https://jsfiddle.net/12apmo5j/12/
I think this solves your problem :)