I'm trying to clear the form onClick with react. The event triggers, but when I try to setState to " " it tells me cannot set state of undefined.
I've tried setting the state to empty in several ways.
onHandleChange(e) {
this.setState({
input: e.target.value
});
}
clearForm(e) {
e.preventDefault();
const input = this.state.input;
console.log("input", input);
this.setState({
input: ""
});
}
I've also tried to do it inline, with onClick={(this.form.elements["text-input"].value = "")}.
<button
className="reset btn btn-danger"
type="reset"
id="resetInput"
value="reset"
onChange={this.onHandleChange}
onClick={this.clearForm}
>
Reset
</button>
My expected output is that the value of the input should be nothing. Empty string. However, that's not happening... i'm not resetting the state.
This happens because you are not binding this correctly to clearForm function.
Cannot set State of undefined. This error means in this.state, this is undefined
Use arrow function to correctly bind this context.
Try this code
clearForm = (e) => {
Try This Code
<script>
$(document).ready(function(){
$('#btnClear').click(function(){
if(confirm("Want to clear?")){
/*Clear all input type="text" box*/
$('#form1 input[type="text"]').val('');
}
});
});
</script>
You can set state for all the values of the form input to be empty strings on click of that clear button.
Related
Currently, I use the following solution:
<button onclick="initiate('ok2')" id="btn1">Initiate</button>
<button id="btn2">Send data</button>
function initiate(ok) {
document.getElementById("btn2").addEventListener("click", receiveData);
}
function receiveData(event) {
console.log(event);
}
The benefit of this approach lies in the named function receiveData, which is recognized as the same function and is not added repeatedly.
Steps to reproduce:
Press the 'Initiate' button multiple times
Press 'Send data'
Result: console log is printed only once
I want to utilize the same approach, but add an attribute to the function. I tried the bind approach, but the event listener is added multiple times. As a result, the console log is also printed multiple times.
Example:
function initiate(ok) {
document.getElementById("btn2").addEventListener("click", receiveData.bind(null, ok));
}
function receiveData(event, ok) {
console.log(event);
console.log(ok);
}
Is it possible to pass an argument to a function and not create duplicate event listeners? Ideally, it would be preferred not to delete event listeners, like in the current solution.
Here is my version with the recommended ways of delegating and setting and getting data attribute
A user cannot click what is not visible so no need to initiate the button, just unhide it
document.addEventListener("click", function(e) {
let btn = e.target
if (btn.matches("#btn1")) {
let targetBTN = document.getElementById(btn.dataset.target);
targetBTN.hidden = false;
} else if (btn.matches("#btn2")) {
console.log(btn.dataset.field);
}
});
<button id="btn1" data-target="btn2">Initiate</button>
<button id="btn2" data-field="ok2" hidden>Send data</button>
// when the window loads add a click handler to the button of choice
window.addEventListener('load', (event) => {
console.log('page is now loaded');
document.getElementById("btn2").addEventListener("click", receiveData)
});
function receiveData(event) {
console.log(event);
}
or as suggested in comments, add the click handler inline.
You need to tel it if it is inited or not..
let data = "";
let init = true;
function initiate(ok) {
data = ok
if(init ){
document.getElementById("btn2")
.addEventListener("click", receiveData);
init = false
}
}
function receiveData(event) {
console.log( data );
}
<button onclick="initiate('ok2')" id="btn1">Initiate</button>
<button id="btn2">Send data</button>
It looks like the one goal is to only allow the second button to be able to be used when the first button is clicked.
So, I attached an event listener to the document. Then used data attributes on the buttons to determine if the start button can be used or not. And just for display I used CSS to hide the start button if its not allowed to be used just yet
document.addEventListener("click",function(e){
let btn = e.target
if(btn.matches(".btn-start")){
let targetBTN = document.querySelector(`[data-id='${btn.dataset.target}']`)
targetBTN.setAttribute("data-initiated","true");
}
else if(btn.dataset.initiated == "true"){
console.log(btn.dataset.field);
}
});
[data-initiated="false"]{
display:none
}
[data-initiated="true"]{
display:inline-block
}
<button data-target="send2" class="btn-start">Initiate</button>
<button data-initiated="false" data-field="ok2" data-id="send2" class="btn-send">Send data</button>
So I'm working in React.JS, and I'm trying to make something like an input field, where a user can enter a number of their choice, and it will show up in the text.
I decided to add a "Reset to zero" button, as an extension.
<div>
Count: {this.state.value}
<form>
<input type="number" value = {this.state.value} onChange = {this.inputChange}/>
<br/>
<button onClick = {this.reset}>reset to zero</button>
</form>
</div>
It works, but it refreshes the page every time it does so.
I read online, and I decided to add "type=button" to my button as so:
<button type="button" onClick = {this.reset}>reset to zero</button>
When I run my code again, it still increments fine, but when I click the button, nothing happens, and when I try to increment it again, I get an error, "TypeError: this.setState is not a function".
The error is coming from this method:
inputChange = event => {
this.setState ({value: event.target.value})
}
I know where the error is coming from, but I don't know why it happened, or how to fix it (note that I'm also a beginner at JavaScript and React.JS)
I hope someone can help me.
Here's my code in entirety, for reference.
class Slider extends React.Component {
constructor(props){
super(props);
this.state = {
value: 0
}
}
inputChange = event => {
this.setState ({value: event.target.value})
}
reset = () => {
this.setState = ({
count: 0
})
}
render() {
return (
<div>
Count: {this.state.value}
<form>
<input type="number" value = {this.state.value} onChange = {this.inputChange}/>
<br/>
<button type = "button"onClick = {this.reset}>reset to zero</button>
</form>
</div>
);
}
}
Thank you guys, in advance.
The reason nothing happens on reset and you are getting that error on input change, is that you are reassigning this.setState in your reset function rather than calling it. Also, you are setting count instead of value, which would lead to the wrong state being set.
This is what your reset function should be:
reset = () => {
this.setState ({
value: 0
})
}
When you call this.setState, React will trigger a re-render in your component with the new state.
That is currently not happening when you click reset. On your subsequent call to inputChange, this.setState has been reassigned with an object, and is no longer callable, throwing that error.
Try replacing your button like this:
<button type = "button"onClick = {this.reset.bind(this)}>reset to zero</button>
This will force the method to execute being this the scope.
I've some buttons on my page. The mockup looks like this
<button type="button" class="js-category-delete" data-id="1">
Delete
</button>
The goal is to get the value of the data-id attribute. Currently I'm using this javascript.
jQuery('.js-category-delete').on('click', (event) => {
let id = jQuery(this).attr('data-id');
});
My problem is that when I log the value to my browser console console.log(id); I the value of the id variable is undefined.
What is wrong with my code?
Using arrow function expression implies the value of this is not the one you intend.
In this case you need to use event.target:
jQuery('.js-category-delete').on('click', (event) => {
let id = jQuery(event.target).attr('data-id');
console.log(id);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button type="button" class="js-category-delete" data-id="1">
Delete
</button>
To suggest you an alternative way:
$('.js-category-delete').on('click', function (event) {
const clickedItem = jQuery(this); // and also jQuery(event.target)
const id = clickedItem.data('id');
console.log(id);
});
The function keyword makes this what you've expected at first.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this
Pen: https://codepen.io/shifu462/pen/WVaGLB
Also, as a shortcut for
jQuery(event.target).attr('data-id');
I've used here another jQuery method to get the value of a data attribute.
jQuery(event.target).data('id');
Docs: https://api.jquery.com/data/
I have a form
<form id="newRecord">
<input type="text" required/>
</form>
<button form="newRecord" type="submit">Submit</button>
http://codepen.io/anon/pen/EZwRjK
When the field is empty, and you click the button, you get a "Please fill out this field." pop up next to the field. Is there a way to detect if that pop up appears with JavaScript?
In HTML5, the pseudo-class :invalid is applied to any input that triggers the "This field is required" dialog box.
If you put the listener on your button, you could find out if the dialog box appeared or not by checking to see if there were any inputs marked :invalid...
$("#newRecord input[type=submit]").click(function() {
if ($("#newRecord input:invalid").length) {
//The popup appeared
} else {
//The popup did not appear
}
});
JSFiddle demo
In fact you can. You can use checkValidity() method. It returns true if the element contains a valid data.
$(function() {
$("#submit-button").click(function () {
// using jquery
console.log($("#input-text")[0].checkValidity());
// using javascript
var input = document.getElementById("input-text");
console.log(input.checkValidity());
});
});
Fiddle
Update
Seems the pop up is not showing when using type="button".
A work around I found is to use $("input").on("blur", function () { instead.
So it should be now:
$(function() {
$("input").on("blur", function () {
console.log($("#input-text")[0].checkValidity());
var input = document.getElementById("input-text");
console.log(input.checkValidity());
// checking as a whole
console.log("Form - ", $("#newRecord")[0].checkValidity());
});
});
Fiddle
REACT / NEXT.JS
In my case, it was because the 'input' tags were required and were not in the viewport (not visible) when submitting on my form.
The form was hidden when a useState was false const [isOpen, setIsOpen] = useState(false), then it was necessary to change the state to true so that the form would appear and the "fill these fields" message.
Solution was with onInvalid() property
<input onInvalid={() => setIsOpen(true)} type='radio' required />
Short Explanation
I want to do something whenever disabled textbox value is changed
Detailed Explanation
I have a disabled text box which value is setting programitically I want to bind the change event of disabled textbox to fire some other function. This is what I tried but won't work.
$('#Rate').change(function() {
// alert("Change Event Called");
CalculateMedicine();
});
$('input[id$=Rate]').bind("change", function () {
CalculateMedicine();
});
This both thing don't work for me and the I don't like the idea to put a function CalculateMedicine() to all the place from which possibly Rate textbox is changing.So apart from this solution any help will be appreciated
assuming that your your input has disable class on on click or something else you check like this
if ($( "#input" ).hasClass( "disable" )) {
Your logics and codes here //
}
//Hope this would help
You can use triggerfor a change event:
<input type="text" disabled="disabled" name="fname" class="myTextBox" ><br>
<input type="button" name="submit" id="submit" value="Submit">
Javascript:
$(".myTextBox").change(function(){
console.log("yes i m working");
});
$("#submit").click("input", function() {
$(".myTextBox").val("New value").trigger("change");
});
Check Demo
It is possible if one redefines the value property of that input.
<html>
<head>
<script>
function Init(){
var tE = document.querySelector('input'); //Our input field.
//We redefine the value property for the input
tE._value = tE.value;
Object.defineProperty(tE, 'value', {
get: function(){return this._value},
set: function(v){
console.log(1, 'The value changed to ' + v)
this._value = v;
this.setAttribute('value', v) //We set the attribute for display and dom reasons
//Here we can trigger our code
}
})
}
function Test(){
//In one second we are going to change the value of the input
window.setTimeout(function(){
var tE = document.querySelector('input'); //Our input field.
tE.value = 'Changed!'
console.log(0, 'Changed the value for input to ' + tE.value)
}, 1000)
}
</script>
</head>
<body onload = 'Init(); Test();'>
<input type = 'text' disabled = 'true' value = 'Initial' />
</body>
</html>
https://jsfiddle.net/v9enoL0r/
The change event will not fire if you change the value programmatically
See https://stackoverflow.com/a/7878081/3052648
A not elegant possible solution:
function checkChanges(){
if(prevRate != $('#Rate').val()){
prevRate = $('#Rate').val();
alert('changed');
}
}
var prevRate;
$(document).ready(function(){
prevRate = $('#Rate').val();
setInterval(function(){
checkChanges();
} ,500);
});
You can fire change event by the following code from wherever you want to fire change event or any other event. The event will be fired either value changed or not. Just place the code after from where you are changing value programatically.
element.dispatchEvent(new Event('change'))
let input = document.querySelector("input");
input.addEventListener("change", () => alert("Change Event is Fired"));
input.value = "xyz";
input.dispatchEvent(new Event("change"));
<input type="text" disabled value="abc">