Form not passing value on submit - javascript

I am struggling with getting my results from an API to show up on HTML page. Does work if the function is executed in the console.
<body>
<div>
<form>
<input type="text" id="search" placeholder="Enter person">
<input type="submit" value="Submit" name="submit" onclick="fetchPerson()" />
</form>
</div>
<div id="app"></div>
JS:
function fetchPerson() {
var input = document.getElementById('search').value;
fetch(`notrevealingapi/api/name=${input}`)
.then(res => res.json())
.then(data => {
console.log(data);
const html = data.data
.map(hit => {
return `<p>Hits: ${hit.person}</p>`;
})
.join("");
document.querySelector('#app').insertAdjacentHTML("afterbegin", html);
})
}

If I understand your need correctly.
you want to populate the result in the <div id="app"> when a user clicks on the submit button.
There is two basic mistakes I can think of.
You should use the button type instead of submit
And use innerHTML instead of the insertAdjacentHTML. So it would look like
document.querySelector('#app').innerHTML = html

Related

Can't get the value of input element

I'm trying to format the value from an input field but I cant get the value
following is the HTML:
<div class="container">
<input type="text" id="search" />
<button id="btn" onclick="search()">Search</button>
</div>
And here is JS code:
var searchValue = document.querySelector('#search').value;
function search() {
console.log(searchValue);
}
Running that code logs empty value but if I remove the .value from querySelector line and use it as
console.log(searchValue.value);
then it works
What is the problem here!?
This is normal you set you variable searchValue outside of your function search() called on click.
Set your variable inside your function called on click.
If you get the value at a moment it has no value it is normal you get no value.
So if you get the value outside of your click function you won't have it. You must use .value at the moment you have a value.
function search() {
var searchValue = document.getElementById('search').value;
console.log(searchValue);
}
<div class="container">
<input type="text" id="search" />
<button id="btn" onclick="search()">Search</button>
</div>
Here as you can see we can read the value, because it has one at the time I am asking for. Above you set the value "in theory" after you clicked.
var searchValue = document.getElementById('search').value;
console.log(searchValue);
function search() {
console.log(searchValue);
}
<div class="container">
<input type="text" id="search" value="TEST"/>
<button id="btn" onclick="search()">Search</button>
</div>
You only update searchValue once when the page is loaded. At this time your text field still contains nothing (strictly an empty string) which is loaded into searchValue.
I assume you want to load it each time your button is clicked, so you need to do this inside search as demonstrated in the example.
function search() {
//Load the value from the text field each time we need it
let searchValue = document.getElementById("search").value;
//Log the value in console
console.log(searchValue);
}
<div class="container">
<input type="text" id="search" />
<button id="btn" onclick="search()">Search</button>
</div>
That should work:
function find()
{
serchValue = document.getElementById("search").value;
console.log(searchValue);
}

How do I send data from a WYSIWYG to a database (Vue.js)

I just started using the Vue2Editor with the intention to replace the many forms that I use to send text and image data to my Firebase database.
My problem is that I cannot get it to add the data entered in the editor.
When using forms, I would just attach an event handler to the form itself and make a function that allowed the transfer.
Example:
<form #submit.prevent="addText">
<label for="fname">First name:</label>
<input type="text" id="fname" name="fname" v-model="fname">
</form>
<button type="submit" variant="success">Save</button>
But when using the Vue2Editor, I do not get any form tags.
I just get a "vue-editor" tag. I tried adding the event handler inside this tag, but nothing happens.
I don't get any errors, but the data is not transferred to the database upon submitting it.
This is the code:
<template>
<div class="container">
<div class="text_editor">
<h2>Add new content</h2>
<vue-editor #submit.prevent="addText" v-model="textblock" />
<button type="submit" class="textblock_btn" variant="success">Save</button>
</div>
</div>
</template>
<script>
import db from '#/firebase/init'
import Vue from "vue";
import Vue2Editor from "vue2-editor";
Vue.use(Vue2Editor);
export default {
name: 'textblock',
data () {
return {
textblock: null
}
},
methods: {
addText(){
db.collection('textblock').add({
textblock: this.textblock
}).then(() => {
this.$router.push({ name: 'Index' })
}).catch(err => {
console.log(err)
})
}
}
}
</script>
You can still wrap the component in a form as the WYSIWYG editor's data is bound to the v-model property.
<form #submit.prevent="addText">
<div class="text_editor">
<h2>Add new content</h2>
<vue-editor v-model="textblock" />
<button type="submit" class="textblock_btn" variant="success">Save</button>
</div>
</form>
Within the addText method you now have this.textblock with the appropriate data on form submission.

Reset for form not working after search has been done

I am trying to reset the form to blank values in the input textboxes after the data filled in the textbox have been searched.
<form id="myForm" class="mt-5" asp-controller="Leave" asp-action="GetAllLeaves">
<div class="form group col-md-6">
<label>Employee </label>
<div class="col">
<input type="hidden" id="employeeId" name="employeeId" />
<input type="text" name="employeeName" id="employeeName" value="#ViewData["CurrentFilterE"]" />
</div>
</div>
<button type="submit" class="btn btn-outline-success">Search</button>
<button type="reset" id="reset" class="btn btn-outline-primary">Reset</button>
</form>
I have tried bunch of different javascripts but none of them work after the search has been completed. They work fine before the search button is clicked. I am aware that there are questions already asked about this here and I have tried those codes but they don't work for me.
These are the different codes that I have tried. They don't work after the search button has been hit. Even refreshing the page does not delete the data in the input boxes.
function myFunction() {
document.getElementById("myForm")[0].reset();
};
$("#reset").click(function () {
$(this).closest('form').find("input[type=text], textarea").val("");
});
document.getElementById("reset").onclick = () => {
document.getElementById("myForm").reset()
};
let inputs = document.querySelectorAll('input');
document.getElementById("reset").onclick = () => {
inputs.forEach(input => input.value ='');
}
in your post method you need to have an IactionResult return type method and then you need to pass property name to ModelState.Remove method, not the value.
Either pass the property name in string, eg. ModelState.Remove("PropertyName"); or in the newer .NET framework, you can use nameof() keyword, eg. ModelState.Remove(nameof(model.Property));
The HTMLFormElement.reset() method restores a form element's default values. This method does the same thing as clicking the form's reset button. If a form control (such as a reset button) has a name or id of reset it will mask the form's reset method. It does not reset other attributes in the input, such as disabled.
https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement/reset.
Your default input value = "#ViewData["CurrentFilterE"]". Reset method restores a form element's default values.
This will help to reset the input:
html:
<form id="myForm">
<input type="text" name="employeeName" id="employeeName" value="test" />
<button id="reset" class="btn btn-outline-primary">Reset</button>
</form>
js:
document.getElementById("reset").onclick = function(e) {
document.getElementById("employeeName").value = "";
}
I ended up using the following
$("#reset").click(function () {
// this for normal <input> text box
$('#employeeName').attr("value", "");
//this for checkbox
document.getElementById('searchAprroved').removeAttribute('checked');
});

Send button value by post request via jquery

My code
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<form>
<button id="test" value="123" name="test" >ok</button>
</form>
<script>
$(document).ready(function () {
$("#test").click(function() {
var combinedData = $("#test").serialize();
$.post(
"element_submit.php",
combinedData
).done(function(data) {
//alert("Successfully submitted!");
$("#result").html(data);
}).fail(function () {
//alert("Error submitting forms!");
})
});
});
</script>
<div id="result" ></div>
The element_submit.php file
<?php
//just to test it should output in the #result div
echo $_POST['test'];
?>
What I am trying to do is submit the with the value="attribute" so the data is serialized and send the post request, it's not like a submit when user insert a value and submit,What I need is to get the value attribute and submit to the php, this code is only for To simplify and illustrate what I am trying to do, because in this page I have the following buttons with ids #follow #unfollow so I need a way to get the button value to make the user follow and unfollow.
you need to serialize the form - not the elements within it .You can also have the triggering button outside the form which will prevent hte form from submitting on the button click.
<form id="testForm">
<input type="hidden" name="testInput" value="123"/>
</form>
<button name="test" id="testButton">submit</button>
...
<script>
$(document).ready(function () {
$("#testButton").click(function() {
var combinedData = $("#testForm").serialize();...
$(document).ready(function () {
$("#testButton").click(function() {
var combinedData = $("#testForm").serialize();
console.log(combinedData);
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="testForm">
<input type="hidden" value="123" name="testinput"/>
</form>
<button id="testButton">Click</button>
Straight JS might help you out. Include a function that sends the id and get the value of that id. Then just send a regular post of the value without serialize... easier.
<script>
function fetchButtonValue(theId){
var p = document.getElementById(theId).value;
alert (p);
}
</script>
<button id="myFormBtn" value ="woo"
onclick="fetchButtonValue(this.id)">My Button</button>
this works...
You could also put a class on the button let's say class="followBTN" then on a click you could just snag the value by $(this).val() I'd use this method if I had more than one button per page.

Inserting new elements to form causing issue when form is sent (empty data)

I have to forms on my website, when second form is filled up (after click save button) im copying this form and inserting it into first form. Unfortunately when I submit this form, data in inserted elements are empty.
My code:
var objToCopy = $('.partnersForm').find('.modal-body').clone();
objToCopy.find('[name]').each(function(){
var objThs = $(this);
objThs.prop('name', '_' + objThs.prop('name'));
objThs.prop('id', '_' + objThs.prop('id'));
});
$('.partnersData').html(objToCopy);
And data looks like this:
[contact_county] => Hampshire
[country] => GB
[contact_title] => 4
[contact_name] => gfhf
[contact_surname] => fghfgh
[_partner_mobile] =>
[_partner_nationality] =>
[_partner_dob] =>
[_partner_email] =>
Where empty data come from inserted elements.
When I remove second form manually after insertion, then everything seems to work.
But I don't understant why I cant send this data even when I change names of inputs.
Simplified HTML structure:
<form id="form1">
<input type="text" name="contact_county" id="contact_county">
<input name="country" id="country">
<input name="contact_title" id="contact_title">
<input name="contact_name" id="contact_name">
<input name="contact_surname" id="contact_surname">
<div class="partnersData" id="partnersData">
<!-- inserted elements goes here -->
</div>
<button type="submit">Submit</button>
</form>
<form class="partnersForm" id="form2">
<div class="modal-body">
<input type="text" name="partner_mobile" id="partner_mobile">
<input type="text" name="partner_nationality" id="partner_nationality">
<input type="text" name="partner_dob" id="partner_dob">
<input type="text" name="partner_email" id="partner_email">
</div>
<div class="modal-foter">
Save
</div>
</form>
Instead of $('.partnersForm').find('.modal-body').clone();, you should use $('.partnersForm').find('.modal-body').clone(true);. When you are making the clone, only the form and associated controls are getting cloned, but the values are getting emptied. Passing "true" as the parameter to clone, the values inside the control will also get cloned.
For details, Check the JQuery Documentation to clone().

Categories