How to send data from table row to post api - html

I have a table in React.
<Table>
<tr>
<td><TextField/></td>
</Table>
<Button onClick={(e)=> submit()}> SUBMIT </Button>
Now i want to send the input of the textField to a post api call when i click the submit button.
const submit = () => {
asyncPost(url, data_to_be_sent).then((response) => {console.log(“ok”)})
I need to send the value i enter in the textfield to the asyncPost. How should i do that?

You have to use hooks (if you use functional component) to be able to store value from <TextField/> inside it. Later you can use it when clicking on a button. You can find an example here
You create hook by:
const [inputValue, setInputValue] = useState(null)
The difference is that you will use onChange event on <TextField/> like:
<TextField onChange={e => setInputValue(e.target.value)} />
so later you can use it like:
const submit = () => {
asyncPost(url, inputValue).then((response) => {console.log(“ok”)})

Related

react js form getting submitted twice

I have below code which calls save form
<div className="col-md-4">
<button onClick={saveCredit} className="btn btn-success">
Submit
</button>
I have onclick handler function as
const saveCredit = () =>{
//validate form
// call api to save form attributes
CreditTransactionDataService.create(data)
.then(response => {
setSubmitted(true);
console.log(response.data);
})
.catch(e => {
console.log(e);
});
}
after successful save , I will show successful message as below.
{submitted ? (
<div>
<h4>You submitted successfully!</h4>
<button className="btn btn-success mr-2" onClick={newCreditTransaction}>
Add
</button><Link style={{ fontWeight: 'bold' }} className="btn btn-warning" to={"/creditTransactionList"}>
return to List
</Link>
</div>
)
but the problem is, my form is getting submitted twice, and creating duplicate records with same values.... couple of save options, i restricted with unique key column at database level, but few tables still need to handled at code level..
I´m unable to reproduce it in codepen, but one solution a little bit hacky could be check in the method if it is submitted already
const saveCredit = {
//Check if it is submitted
if(!submitted){
//validate form
// call api to save form attributes
CreditTransactionDataService.create(data)
.then(response => {
setSubmitted(true);
console.log(response.data);
})
.catch(e => {
console.log(e);
});
}
}
This may not be the best but could do the job
Also a thing I did notice is that your saveCredit function not look like a function.
Why not declare as an arrow function? Like:
const saveCredit = () => { //Your code }
Your button doesn't need onClick event handler if it's responsible for submitting a certain form. You should add type="submit" to button and onSubmit to form tag itself.
You should go for this approach to handle submitting correctly (clicking of the button or hitting enter by the user are covered).

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.

Is there a way to use EJS variables in HTML inputs?

I am trying use a check box to send all selected users to a new page and am wondering how this could be done (using mongodb to store information) My existing code is as follows,
first I render the page
router.get("/admin", ensureAuthenticated,(req, res) => {
User.find()
.then(user => {
res.render("admin", {
user: user,
});
})
});
For all of the users the website has I create a check box, and all selected users should get sent to a new page
<% for (i in user) { %>
<form action="/admin" method="POST">
<label for="checkbox"><%=user[i].name%></label>
<input type="checkbox" id="user" name="user">
</form>
<% } %>
<button type="submit">View Profile</button>
however when I console log it says that user info is undefined.
router.post("/admin", (req, res) => {
profile = req.body.name
console.log(`user info: ${profile}`)
res.redirect("/admin/userprofile")
router.get("/admin/userProfile", ensureAuthenticated,(req, res) => {
res.render("admin_user_profile", {
user: profile
})
});
})
any help will be greatly appreciated, thanks
Your page contains one <form> element per user but only one submit button overall. Either include the submit button in the <form>, but then you can only submit one of the users. Or move the <form> and </form> outside the for loop (and </form> after the submit button) and give every <input> a unique name, for example,
<input type="checkbox" id="<%=user[i].name%>" name="<%=user[i].name%>">
Then you can submit all checkboxes at once.
Next, your server-side code refers to req.body.name, where should that come from? req.body should contain one entry per user name, with the names of your <input> elements. And req.body.firstusername === "on" if the corresponding checkbox was selected.
In other words, you should get an object like
req.body = {
"firstusername": "on",
"thirdusername": "on"
}
if the first and third usernames are selected and the second is not selected.

click event in subscribe method angular 2

I have 2 button one of them of type file -which is hidden- if the user click the first button a confirmation dialog opens if user click Ok the second button must be clicked.
The problem is that all the logic is subscribe method -of confirmation dialog - are execute expect clickEvent for the second button.
Can anyone explain why and provide me with a solution?
#ViewChild('fileBrowser') fileInput: ElementRef;
dialogRef: MdDialogRef<ConfirmationDialog>;
clickUpload(){
this.dialogRef = this.dialog.open(ConfirmationDialog);
this.dialogRef.afterClosed().subscribe((result) => {
if (result) {
// some code
this.fileInput.nativeElement.click();
}
this.dialogRef = null;
});}
//HTML Code
<button md-button (click)="clickUpload()" > upload</button>
<input #fileBrowser id="fileBrowser" type="file" hidden="true">
"this.fileInput.nativeElement.click();" this is the problem line
I found the solution, i changed dialogRef's method from afterClosed to beforeClose
The new code
this.dialogRef.beforeClose().subscribe((result) => {
if (result) {
// some code
this.fileInput.nativeElement.click();
}
this.dialogRef = null;
});}

Saving vs. submitting a form

I am working on an application process using Laravel 4.2.
Users applying with my form need to be able to save their form input for later, or submit it. So right now I have two different buttons, Save and Submit.
The key difference between saving and submitting would be a status. When a user saves their application, their application status will be marked as "in progress", when they submit their application the status would be marked as "completed".
My question is:
In terms of my form HTML structure, How do I differentiate between a saved and submitted application? Just checking whether or not they have filled out all the required inputs would not be reliable, because there is the possibility that the user wanted to add more to it later.
I tried doing a form inside of a form, but quickly realized this would not work.
Does anyone have an idea as to how to accomplish this?
You can have two submit buttons inside a form with different names and values:
<button type="submit" name="action" value="save">Save</button>
<button type="submit" name="action" value="submit">Submit</button>
You can then check the value in your controller action:
public function postSubmission()
{
if (Request::get('action') == 'save')
{
// Save form for later
}
elseif (Request::get('action') == 'submit')
{
// Immediately submit form
}
}
Lets say your code is something like this (this is from Laravel5 but as far as i remember it's mostly the same).
{!! Form::open(array('route' => array('admin.editApplication'), 'method' => 'PATCH')) !!}
....
<button type="submit" name="save" value="save">Save</button>
<button type="submit" name="edit" value="edit">Edit</button>
{!! Form::close() !!}
Then in your controller you can do something like this (check if the value is set in edit (you might want to call it something else than edit and save)
public function editApplication(Request $request) {
if(isset($request->input('save')){
// Your code to save here
}else{
// Your code to edit here.
}
}