I'm making a web app with react and in one of my functions I fetch some data from the backend and then I show it to the user by changing the value of the textarea. The problem is that I want the textarea not to be edited when the user presses a button to fetch the data from the backend but then if I click the textarea I want it to erease the data fetched and allow the user to write into itself.
This is how the code looks like in the component that contains the textarea:
<div id="text-div" onClick={this.onWrite}>
<textarea id="text" rows={13} value={this.state.value} onChange={this.handleChange}></textarea></div>
<Button onClick={this.handleRead}>Read</Button>
//functions within the code
onWrite() {
// do stuff
document.getElementById("text").setAttribute("contentEditable", true);
}
async handleRead() {
// fetches data and saves it into this.state.value
document.getElementById("text").setAttribute("contentEditable", false);
}
I've also tried using readOnly but it doesn't work either, when I call handleRead() it doesnt let the user write and shows the data (as expected) but when i call onWrite() (it would set readOnly property to false) it does not let the user write. So I cant revert what handleRead() did.
I would really appreciate some suggestions because I'm kind of a noob in React and this is my first project, sorry if I missed something.
contenteditable is an attribute added to non-editable fields like div to make them editable
You want to use readonly or disabled
I converted your example to vanilla to make it usable here
function onWrite() {
// do stuff
document.getElementById("text").removeAttribute("readonly");
}
async function handleRead() {
document.getElementById("text").value = 'test'
document.getElementById("text").setAttribute("readonly", true)
}
<div id="text-div" onclick="onWrite()">
<textarea id="text" rows="13"></textarea>
</div>
<button onclick="handleRead()">Read</button>
This might be because you have already assigned some value to your input field.
So use defaultValue instead of value
So try writing your code like this
<div id="text-div" onClick={this.onWrite}>
<textarea id="text" rows={13} defaultValue={this.state.value} onChange={this.handleChange}>
</textarea>
</div>
<Button onClick={this.handleRead}>Read</Button>
This should solve your problem.
Related
Whenever I run the code it brings me to the webpage and everything appears fine but when I submit a value wihtin the text box, nothing happens. It just restarts the webpage with the submission and thats it. I don't get any of the alerts in the code.
My Code: CODE
I tried putting the into the head or the body and still no change. I tried changing values and changing orders but still nothing. I'm pretty certain I'm not spelling anything incorrectly because I did't get any red underlines and I looked over the code a couple times and didn't notice any misspellings. I expect to have one the three alerts to appear whenever a value is submitted on the webpage.
I'm sure you're still learning the basics, but this is something you should watch tutorials on, and maybe look at other people's code to get a better understanding of how JavaScript works.
All you need is the preventDefault() function, that can be run on an event, like submit. This is really only important in the case of forms. Here's how the preventDefault() function works:
const form = document.querySelector('form'),
responseList = document.querySelector('ul')
form.addEventListener('submit', (e) => {
e.preventDefault()
const inputs = e.target.querySelectorAll('input')
inputs.forEach(input => {
const responseOutput = document.createElement('li'),
{name, value} = input
responseOutput.innerText = `${name}: ${value}`
responseList.appendChild(responseOutput)
})
})
<form>
<input type="text" name="Anything" />
<br>
<input type="text" name="Something Else" />
<br>
<button type="submit">Submit</button>
</form>
<br>
<div>
<span>Response:</span>
<ul></ul>
</div>
I should also mention, that in your case, you should switch to using an `onsubmit` on the `` rather than an `onclick` on the ``. It will make it more clear. That is, if you don't want to use an `addEventListener()` like I use in my example.
i'm trying to update a hidden input with an entered value from a SweetAlert modal (basically a prompt).
The code below does not work, the form submits but the hidden field value is null.
HTML:
<input type="hidden" name="input" v-model="value">
JavaScript:
this.value = websiteId;
event.target.submit();
The below code however does seem to work! But not really much point in using Vue.js if i'm going to just plain old JavaScript.
HTML:
<input type="hidden" class="input-value-web" name="input" value="0">
JavaScript:
document.querySelector('.input-value-web').value = websiteId;
event.target.submit();
When you change the value of a Vue instance's data property, like you're doing with this.value = websiteId, that bound property won't update the value of the <input> until the Vue instance's next update.
However, the next update won't occur until after everything in the method has been executed.
To get around this, use the $nextTick method to wait until the Vue instance has updated before executing event.target.submit().
Here's an example:
methods: {
submitForm() {
this.value = websiteId;
this.$nextTick(() => {
event.target.submit();
});
}
}
So this is probably an easy one, but I'm just not doing it right. My goal is to send the user input from this textbox:
<input type='text' placeholder='Form Name...' id='formNameInput' required>
Into this Div:
<div id="code_output"></div>
I'm trying to make it appear in real time, and so far I used this to try and do so, but it doesn't work:
document.getElementById("code_output").innerHTML += document.getElementById("formNameInput").value;
Why doesn't it show? Does my code need something to trigger the Javascript?
You're close, but the issue is that you're not using an event handler. The script is executing your code once, as soon as possible (before you have the chance to enter anything into the text input). So, you have to add some sort of event listener so that the copying happens at the appropriate time. Something like below:
document.getElementById('formNameInput').addEventListener('keyup', copyToDiv);
function copyToDiv() {
document.getElementById("code_output").innerHTML = document.getElementById("formNameInput").value;
}
<input type='text' placeholder='Form Name...' id='formNameInput' required>
<div id="code_output"></div>
You need to do that whenever the value of formNameInput changes. For that you need an event.
Your code should look like:
document.getElementById("formNameInput").addEventListener('input', function () {
document.getElementById("code_output").innerHTML += this.value;
});
function change() {
document.getElementById("code_output").innerHTML = document.getElementById("formNameInput").value;
}
document.getElementById('formNameInput').onkeyup = change
maybe this is what you are trying?
You need to attach an event listener to your input that executes a function any time an input event occurs on the field:
formNameInput.addEventListener('input', function(e) {
code_output.textContent = e.target.value
})
<input type="text" placeholder="Form Name..." id="formNameInput" required />
<div id="code_output"></div>
Please note that the above code takes advantage of the fact that browsers automatically create a global variable for each element with a unique id attribute value, and this variable has the same name as the value of the id.
If the concept of events is new to you, this might be a good place to get started:
https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Building_blocks/Events
I'm newbie in making atom plugins. I have to make a field which will take an input. I'm using etch for component management. In the render method, I've made this input field
<input
name={'component'}
type={'text'}
onchange={this.onInputChange}
value={this.componentName}
/>
I've made this onInputChange method which looks like :
onInputChange = (event) => {
this.componentName = event.target.value;
etch.update(this);
}
but I'm getting an event which comes after some time (kinda debounced event), furthermore I'm not able to delete the text from input. What is the right way to make an input.
<div class="native-key-bindings">
<input/>
</div>
Try wrapping it in this way. It will also fix the delete issue.
I need to clear the default values from input fields using js, but all of my attempts so far have failed to target and clear the fields. I was hoping to use onSubmit to excute a function to clear all default values (if the user has not changed them) before the form is submitted.
<form method='get' class='custom_search widget custom_search_custom_fields__search' onSubmit='clearDefaults' action='http://www.example.com' >
<input name='cs-Price-2' id='cs-Price-2' class='short_form' value='Min. Price' />
<input name='cs-Price-3' id='cs-Price-3' class='short_form' value='Max Price' />
<input type='submit' name='search' class='formbutton' value=''/>
</form>
How would you accomplish this?
Read the ids+values of all your fields when the page first loads (using something like jquery to get all "textarea", "input" and "select" tags for example)
On submit, compare the now contained values to what you stored on loading the page
Replace the ones that have not changed with empty values
If it's still unclear, describe where you're getting stuck and I'll describe more in depth.
Edit: Adding some code, using jQuery. It's only for the textarea-tag and it doesn't respond to the actual events, but hopefully it explains the idea further:
// Keep default values here
var defaults = {};
// Run something like this on load
$('textarea').each(function(i, e) {
defaults[$(e).attr('id')] = $(e).text();
});
// Run something like this before submit
$('textarea').each(function(i, e){
if (defaults[$(e).attr('id')] === $(e).text())
$(e).text('');
})
Edit: Adding some more code for more detailed help. This should be somewhat complete code (with a quality disclaimer since I'm by no means a jQuery expert) and just requires to be included on your page. Nothing else has to be done, except giving all your input tags unique ids and type="text" (but they should have that anyway):
$(document).ready(function(){
// Default values will live here
var defaults = {};
// This reads and stores all text input defaults for later use
$('input[type=text]').each(function(){
defaults[$(this).attr('id')] = $(this).text();
});
// For each of your submit buttons,
// add an event handler for the submit event
// that finds all text inputs and clears the ones not changed
$('input[type=submit]').each(function(){
$(this).submit(function(){
$('input[type=text]').each(function(){
if (defaults[$(this).attr('id')] === $(this).text())
$(this).text('');
});
});
});
});
If this still doesn't make any sense, you should read some tutorials about jQuery and/or javascript.
Note: This is currently only supported in Google Chrome and Safari. I do not expect this to be a satisfactory answer to your problem, but I think it should be noted how this problem can be tackled in HTML 5.
HTML 5 introduced the placeholder attribute, which does not get submitted unless it was replaced:
<form>
<input name="q" placeholder="Search Bookmarks and History">
<input type="submit" value="Search">
</form>
Further reading:
DiveintoHTML5.ep.io: Live Example... And checking if the placeholder tag is supported
DiveintoHTML5.ep.io: Placeholder text
1) Instead of checking for changes on the client side you can check for the changes on the client side.
In the Page_Init function you will have values stored in the viewstate & the values in the text fields or whichever controls you are using.
You can compare the values and if they are not equal then set the Text to blank.
2) May I ask, what functionality are you trying to achieve ?
U can achieve it by using this in your submit function
function clearDefaults()
{
if(document.getElementById('cs-Price-2').value=="Min. Price")
{
document.getElementById('cs-Price-2').value='';
}
}