Auto-type in html input - html

I want to have two input fields. It should be possible to type in one of them, but the other one should be hidden. whatever we type in the first field should be auto-typed in the hidden one. Is this possible?

just add type='hidden' for the second input
const input = document.getElementById('input')
const hiddenInput = document.getElementById('hiddenInput')
input.addEventListener('input', ({ target: { value } }) => hiddenInput.value = value)
<input id='input'/>
<input id='hiddenInput'/>

Related

radio buttons is not functioning properly

a division has a checkboxs and by clicking that checkbox radio buttons options need to be shown for a particular checkbox
checkbox is mapped as according to the array
<form id="lab_test_detail">
{item.subcategory.map((item, index) =>
<>
<input type={"checkbox"} onChange={() => handleChange(item, index)} name={item.id}></input>
<label style={{ position: "inherit", zIndex: "10" }}>{item.categoryname} </label>
<div id={index}></div>
</>
)}
</form>
when the checkbox is changed radio buttons option should have to populate on
handleChange is
const handleChange = (item, index) => {
httpClient.GET(`medical-institute/categoryId/${item.id}`, false, true)
.then(resp => {
// debugger;
document.getElementById(index).innerHTML =
`
${
resp.data.data.map((item1,index1)=>{
return`<form>
<input type="radio" onChange=${handleRadioChange(item,index)}></input>
<label >${item1.medicalinstitutename}</label>
<span> Rs.${item1.price}</span>
<br/>
</form>
`
})
}
`
console.log("response is", resp.data.data)
})
}
const handleRadioChange = (item, index) => {
console.log("inside radiochange")
console.log("dasdas", item, index)
}
so when radio button is clicked i need to do a particular thing but handleRadioChange is called when i click on the checkox but not when i click on radio , why is this happening, a ny solution?
Because you are executing the handleRadioChange once the node is added into the DOM.
Change the onChange handler
handleRadioChange(item,index)
to
() => handleRadioChange(item,index)
You should try to work with the virtual DOM instead of insert html string.
In your case, I think you can use state to store the item data for display and trigger the re-render. BTW you might don't have to fetch the data every time user clicks a check box.

How do I add components dynamically in React?

In the attached picture, I want a different component to be added below the 'Choose Round Type' option based on the round type selected.
Adding to a single round is no issue. But when I add a new round and try to do the same for it, the components are essentially the same thing but repeated.
As you can see here, both of the forms are either visible or not.
I am following a wrong approach wherein I just add the form component to the mapped round and because the form is same for every round, it connects to all of the forms of the other rounds.
What I want is that I should be able to select different round types and get the corresponding input fields in every round.
As visible, once I click on a different round type in the second round, the first one also changes.
The Add a Round functionality is made using AntDesign Components.
What I tried to do:
import React, { useState } from "react";
import { useStore } from "react-redux";
import { Input, Radio, Form, Button, Space } from 'antd';
import { MinusCircleOutlined, PlusOutlined } from '#ant-
design/icons';
import "./createQuizPage.css";
const RoundTypeScheme = ({ type, count }) =>
{
console.log(type, count);
try
{
switch(type)
{
case "Pounce":
return (
<div id = {count}>
<label>Marks for correct answer (Direct)
</label>
<Input size = "small" />
<label>Marks for incorrect answer (Direct)
</label>
<Input size = "small" />
<label>Marks for correct answer (Pounce)
</label>
<Input size = "small" />
<label>Marks for incorrect answer (Pounce)
</label>
<Input size = "small" />
<hr />
</div>
);
case "Pounce + Bounce":
case "Differential":
case "Buzzer":
case "Long Visual Connect":
default:
return (<></>)
}
}
catch(err)
{
console.log(err);
}
}
const CreateQuizPage = () =>
{
const [type, setType] = useState("");
const [count, setCount] = useState(0);
const store = useStore();
let quiz_name = store.getState().quiz;
const quiz_rounds = ["Preliminary", "Main"]
const quiz_sub_rounds = ["Pounce", "Pounce + Bounce", "Buzzer", "Differential", "Long Visual Connect"]
const roundScores = (e) =>
{
setType(e.target.value);
}
const addRound = () =>
{
setCount(prev => (prev + 1));
}
return (
<div id = "createQuizPage">
<Form
name="basic"
className = "createQuizPage__form"
>
<h1>Name: {quiz_name}</h1>
<Form.Item>
<label>Choose Quiz Type </label>
<Radio.Group
options = {quiz_rounds}
optionType = "button"
buttonStyle = "solid"
className = "createQuizPage__type-button"
></Radio.Group>
</Form.Item>
<Form.List name="users">
{(fields, { add, remove }) => (
<>
{fields.map(({ key, name, fieldKey, ...restField }) => (
<Space key={key} align="baseline" className = "createQuizPage__quiz-round">
<Form.Item
{...restField}
name={[name, 'round_type']}
fieldKey={[fieldKey, 'round_type']}
rules={[{ required: true, message: 'Missing Quiz Round' }]}
>
<label>Choose Round Type </label>
<Radio.Group
options = {quiz_sub_rounds}
optionType = "button"
buttonStyle = "solid"
onChange = {(e) => roundScores(e)}
></Radio.Group>
<RoundTypeScheme type = {type} count = {count}/>
</Form.Item>
<MinusCircleOutlined onClick={() => remove(name)} />
</Space>
))}
<Form.Item>
<Button onClick={() => {add(); addRound();}} icon={<PlusOutlined />}>
Add a Round
</Button>
</Form.Item>
</>
)}
</Form.List>
</Form>
</div>
)
}
export default CreateQuizPage;
The issue you facing is caused because you pass the type and view dependencies as props to the actual component and they're still reactive.
You need to either:
Save the initial config of the round component and then if the props will change, it won't change the UI of the round.
Hold in the container component an array of the round configs and then loop over them and pass each round config to the round component.
I think #2 would be better in terms of architecture and code readability

Concat Form Field Values

Hopefully I'm not repeating this question in anyways. But I am trying to get a form section with its name values and field vales to put as a single concat string. So like
Form Input:
First Name: John
Last Name: Smith
Fields 5 - 10.. etc
String Output:
FirstName=John&LastName=Smith&Field2=Value2&Field_etc=Value_etc
I tried
var inputArray = $("form#form :input").each(function () {
var input = $(this);
console.log(input.attr('name') + ":" + input.val());
});
Which outputs a test value correctly in the console.log as
firstName:John
lastName:Smith
but I'm struggling on the next bit of code that will help console.log it as a combine array string. Not sure if this is a for loop or something that helps the next step.
See comments in code below, maybe this might help you get on the right track...
The main cool thing here is to store submission data as an object and then use $.param() to convert submission to url string.
// on form submit
$(document).on('submit', '#form', function(e) {
// prevent form default submit action
e.preventDefault();
// set empty submission object
let submission = {};
// for each of this form submit event target object entries as key/field
for (const [key, field] of Object.entries(e.target)) {
// if object entry (field) has a name attribute
if (field.name) {
// add name/value to submission object
submission[field.name] = field.value;
}
}
// convert submission object to url params string
var paramsStr = $.param( submission );
// log the string
console.log(paramsStr)
});
<form id="form">
<input name="firstName" value="John" type="text" />
<input name="lastName" value="Smith" type="text" />
<input name="userName" value="johnsmith" type="text" />
<button type="submit">Submit</button>
</form>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Loop through the input elements and concatenate the name and value:
const inputs = document.querySelectorAll('#form input')
let msg
inputs.forEach(inp => {
inp.onkeyup = () => {
msg = 'String Output: '
inputs.forEach(i => msg += `${i.name}=${i.value}&`)
console.clear()
console.log(`\r\n${msg.slice(0, -1)}\r\n\r\n`)
}
})
input {
display: block;
margin-bottom: 8px;
font:18px/1.2em Arial;
}
<form id='form'>
<input name='FirstName' placeholder='First Name' />
<input name='LastName' placeholder='Last Name' />
<input name='Example1' placeholder='Example 1' />
<input name='Example2' placeholder='Example 2' />
</form>

How to add zeros into HTML input?

I have a html input that has a fixed length of 7.
If the users types 1234, how can I prefix this input with a number of zeros in order to have the required length of 7?
I want to do this only in the UI because I already have a method in ts code for prefixing with zeros this input in order to send this correctly to backend.
<input formControlName="userNumber" type="text" class="form-control" placeholder="User #" aria-label="userNumber" aria-describedby="userNumber">
You can make use of input event on input field. Once user enters some numbers and then when the input field loses focus, required number of zeroes will be added.
const $input = document.querySelector('input');
$input.addEventListener('change', (e) => {
const value = e.target.value;
const length = e.target.value.length;
if (length === 0) {
$input.value = value;
}
else if (length < 7) {
$input.value = '0'.repeat(7-length) + value;
}
});
<input formControlName="userNumber" type="text" class="form-control" placeholder="User #" aria-label="userNumber" aria-describedby="userNumber">

Set to empty value to event.value inside of onChange from outside button

I have an input element that has a type of file:
<input
id="archiveInput"
type="file"
// eslint-disable-next-line no-return-assign
ref={ref => (this.uploadArchive = ref)}
style={{ display: 'none' }}
onChange={this.onChangeUploadFile}
/>
In the onChange method, I set event.value to ""(empty string) because it is possible to upload the same file again.
So, I also have button that resets all form elements.
How can I set event.value to empty string when I click the button?
You may clear input value using following:
event.target.value = null;
Also, you can use reference to clear
this.uploadArchive.value = "";