React js Execute function on submit - javascript

I have a simple search box on my react app. The box should let the user input a phrase, and then execute another react.js function when they hit the enter key. I have tried every combination (put box in a form, not in a form, onSubmit, etc), but I can't seem to stop the page from "reloading" when the user inputs the information and presses enter.
HTML:
<input className="input" placeholder="Type it Here..." type="text" name="key" id="searchgrid" />
React JS Code:
searchForMatches(){
var value = document.getElementById("searchgrid").value;
console.log(value);
}
I just need the searchForMatches() function to run when the user types the enter key into the search box.
Thanks.

EDIT
Yes, you get the key pressed with onKeyPress event in element
Check the snippet
var Comp = React.createClass({
searchForMatches(e) {
var value = String.fromCharCode(e.charCode)
this.setState({
keyPressed: value
})
},
getInitialState() {
return ({
keyPressed: ''
})
},
render() {
return ( < div >
< label > Last Key Pressed: {
this.state.keyPressed
} < /label><br / >
< input className = "input"
placeholder = "Type it Here..."
type = "text"
name = "key"
id = "searchgrid"
onKeyPress = {
this.searchForMatches
}
/>
</div >
)
}
})
ReactDOM.render( < Comp / > , document.getElementById('foo'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id='foo'></div>
Check the system events on React JS (https://facebook.github.io/react/docs/events.html)

For Search Options you can do the following :
HTML :
<div class="pull-right" style='display:block;'>
<span style="color:red"><strong>Search Products</strong></span>
<form method="get">
<input name="keysearch" value="" placeholder="name" id="keysearch" type="text" class="form-control">
<span id="loading"></span>
</form>
<div id="result"></div>
</div>
SCRIPT USED :
<script>
$(document).ready(function(){
var req = null;
$('#keysearch').on('keyup', function(){
var key = $('#keysearch').val();
if (key && key.length > 0){
$('#loading').css('display', 'block');
if (req)
req.abort();
req = $.ajax({
url : 'fetch_records.php',
type : 'GET',
cache : false,
data : {
keysearch : key,
},
success : function(data)
{
console.log(data)
if (data)
{
$('#loading').css('display', 'none');
$("#result").html(data).show();
$("#result").css('position', 'absolute');
$("#result").css('z-index', '1');
// style='display:block; position :absolute; z-index:1'
}
}
});
}
else
{
$('#loading').css('display', 'none');
$('#result').css('display', 'none');
}
});
});
</script>
PHP fetch-records.php File:
<?php
$conn = mysqli_connect('localhost','root', '','Name_OF_DB');
if(isset($_GET['keysearch']))
{
$search = $_GET['keysearch'];
$search = mysqli_real_escape_string($conn,$search);
// $data = "SELECT * FROM products ";
$data = "SELECT * FROM products WHERE product_title LIKE '%{$search}%' order by product_id ";
// $query = query ("SELECT * FROM products WHERE product_category_id = ".$id." ORDER BY product_price DESC");
$result = mysqli_query($conn,$data);
if (mysqli_num_rows($result)>0)
{
while($row= mysqli_fetch_assoc($result))
{
echo"<a href='create_a_new_page_brother.php?id={$row['product_id']}&price=0' class='list-group-item'>{$row['product_title']}</a>";
}
}
}
?>

Related

remember checkbox and radio button state after page reload

I am making a filter with jQuery and Laravel (PHP). It filters the data when I click the checkbox or radio button but, if I click checkbox or radio button and refresh the page the state of checked checkbox or radio button will no longer remain. I want the checked state to remain even after the page reloads.
This is my code.
<div class="search">
<input type="radio" name="expertise[]" value="backend" />programmer
<input type="radio" name="expertise[]" value="frontend" />programmer
</div>
<div class="avail">
<p>
<input type="checkbox" name="available[]" value="20" />20
</p>
<p>
<input type="checkbox" name="available[]" value="30" />30
</p>
</div>
jQuery
<script>
var expertise = [];
var available = [];
$(document).on('change', 'input[name="expertise[]"], input[name="available[]"]', function(e) {
e.preventDefault();
types = [];
available = [];
if (document.location.href.indexOf('filter') > -1) {
var url = '../developers/filter?type=dev';
} else {
var url = '/developers/filter?type=dev';
}
$('input[name="type[]"]:checked').each(function() {
expertise.push($(this).val());
url = url + '&expertise=' + $(this).val();
});
$('input[name="available[]"]:checked').each(function() {
available.push($(this).val());
url = url + '&available=' + $(this).val();
});
if (document.location.href.indexOf('filter') > -1) {
$.get('../developers/filter', {
type: 'dev',
expertise: expertise,
available: available,
}, function(markup) {
$('.dev-holder').html(markup);
});
} else {
$.get('developers/filter', {
type: 'dev',
expertise: expertise,
available: available,
}, function(markup) {
$('.dev-holder').html(markup);
});
}
window.history.pushState("", "", url);
});
</script>
Laravel controller
public function search(Request $request)
{
$type = $request->get('expertise');
$availability = $request->get('available');
$url = 'filter';
$users = User::where('type','dev')->where('is_approved', '=', 1);
if (!empty($type)) {
$users = $users->where('expertise','dev');
}
$users->when($availability, function ($query, $availability ) {
return $query->where(function ($whereQuery) use ($availability ) {
foreach ($availability as $item) {
$whereQuery->orWhere('avaibility', 'LIKE', $item);
}
});
});
You are already pushing things to the URL so when you load the page you can check the url query string for what's set or not.
$(function () {
var urlSearchParams = new URLSearchParams(window.location.search);
if (urlSearchParams.get('expertise[]')) {
$('input[name="expertise[]"][value="'+urlSearchParams.get('expertise[]')+'"]').prop('checked', true);
}
urlSearchParams.getAll('available[]').forEach(function (val) {
$('input[name="available[]"][value="'+val+'"]').prop('checked', true);
});
});
Note that the URLSearchParams needs to be polyfilled in IE
This can also be achieved via the HTML and Laravel:
<div class="expertise">
<input type="radio" name="expertise[]" id="backend" value="backend"
{{in_array('backend', request()->input('expertise',[])) ? 'checked' : ''}} />Backend
<input type="radio" name="expertise[]" id="frontend" value="frontend"
{{in_array('frontend', request()->input('expertise',[])) ? 'checked' : ''}}/>Frontend
</div>
<div class="availability">
<p>
<input type="checkbox" name="available[]" value="above30"
{{in_array('above30', request()->input('available',[])) ? 'checked' : ''}}
/>Above 30 hrs/week
</p>
<p>
<input type="checkbox" name="available[]" value="below30"
{{in_array('below30', request()->input('available',[])) ? 'checked' : ''}}
/>Below 30 hrs/week
</p>
</div>
This is assuming you have this HTML in a .blade.php file
U can use local storage for saving the state. Suppose if check box is clicked then store it in local storage and if page reloads make a function to extract data from the local storage and apply it.
JS/jQuery: Save into localStorage
PHP/Laravel: Save in session,
session_start();
if (!isset($_SESSION['vals']) {
$_SESSION['vals'] = 'default=stuff'
}
$_SESSION['vals'] //access it like this
and then you can change it when they submit
,
//set
let values = ["yes"]
localStorage.setItem('vals',JSON.stringify(values))
//retrieve
let result = localStorage.getItem('vals')
result = JSON.parse(result)
//use
if (result[0] = "yes") {
yourradiothing.checked = true
}
You can also store other things.

Can't Remove Data because of Child Reference Error?

I have a user structure where I can create and update a user but I cannot remove a user due to a reference child error due to some kind of string.
Basically, I have a realtime database consists of different users ID then there's the Name, Age and Nationlaity.
I want to be able to try and delete a user by its user ID for instance (usr5) so that when I enter that it'll delete the user from the database.
Can anyone help?
The Error:
Reference.child failed: First argument was an invalid path = "[object HTMLInputElement]". Paths must be non-empty strings and can't contain ".", "#", "$", "[", or "]"
at fi (validation.ts:382)
at o.child (Reference.ts:90)
at removeUser ((fie path folders) index.html:115:58)
My HTML:
<body>
<div>
<h4>Create User: </h4>
<form>
<label>Create User ID: </label><input type="text" id="usrID"/><br/>
<label>First Name: </label><input type="text" id="usrFName"/><br/>
<label>Age: </label><input type="number" id="usrAge"/><br/>
<label>Nationality: </label>
<select id="usrNation">
<option value="American">American</option>
<option value="British">British</option>
<option value="French">French</option>
</select>
<button id="createUserBtn">Create</button>
</form>
</div>
<div>
<h4>Remove User: </h4>
<form>
<label>Create User ID: </label><input type="text" id="usrID"/><br/>
<button id="removeUserBtn">Remove</button>
</form>
</div>
My Firebase/Javascript:
<script>
var database = new Firebase("https://(my db url)/"),
userdb = database.child("/users");
userID = document.getElementById('usrID'),
userFirstName = document.getElementById('usrFName'),
userAge = document.getElementById('usrAge'),
userNationality = document.getElementById('usrNation');
function createUser(userID, usrFName, usrAge, usrNation){
firebase.database().ref('users/' + userID).set({
usrFName: usrFName,
usrAge: usrAge,
usrNation: usrNation
});
console.log('Success');
}
function insertAutoKey(usrFName, usrAge, usrNation){
var newPost = {
usrFName: usrFName,
usrAge: usrAge,
usrNation: usrNation
};
var newPostKey = firebase.database().ref().child('users').push().key;
var updates = {};
updates['/users/' + newPostKey] = newPost;
return firebase.database().ref().update(updates);
}
document.getElementById('createUserBtn').addEventListener('click', function(){
var usrID = userID.value,
usrFName = userFirstName.value,
usrAge = userAge.value,
usrNation = userNationality.value;
if(usrID && usrFName && usrAge && usrNation) {
createUser(usrID, usrFName, usrAge, usrNation);
}
});
function removeUser(){
var userRef = firebase.database().ref().child("users").child(userID);
userRef.once('value', function(snapshot) {
if (snapshot.val() === null) {
alert("no user found");
}else{
userRef.remove();
}
});
console.log('Remove Success');
}
document.getElementById('removeUserBtn').addEventListener('click', function(){
removeUser();
});
Change this:
userID = document.getElementById('usrID'),
userFirstName = document.getElementById('usrFName'),
userAge = document.getElementById('usrAge'),
userNationality = document.getElementById('usrNation');
into this:
userID = document.getElementById('usrID').value;
userFirstName = document.getElementById('usrFName').value;
userAge = document.getElementById('usrAge').value;
userNationality = document.getElementById('usrNation').value;
You need to add the property value to retrieve the value of each element.

How to apply foreach array function in for below code for selected action

This is the code of the file app.js in Laravel. I want convert multiple or condition of selectedAction into JavaScript array function. I am new to JavaScript so I don't know.
$('#page_hr_applicant_edit .applicant-round-form').on('click', '.round-submit', function() {
let button = $(this);
let form = $(this).closest('.applicant-round-form');
let selectedAction = $(this).data('action');
if (selectedAction == 'confirm' || selectedAction == 'send-for-approval' ||
selectedAction == 'onboard' || selectedAction == 'approve') {
if (!form[0].checkValidity()) {
form[0].reportValidity();
return false;
}
}
form.find('[name="action"]').val(selectedAction);
button.prop('disabled', 'disabled').addClass('disabled');
form.submit();
});
You can define array with all possible values of actions, Instead of or you can use indexOf method which will return index of your action. If index is 0 or greater than 0 means the item is found in array else it is not found in array. Below is the sample code for converting the or logic to array
const actions = [ 'confirm', 'send-form-approval', 'onboard', 'approve' ];
if(actions.indexOf(selectedAction) >= 0) {
// Action is found in array
}
else {
// Unknown action i.e. Action is not found in array
}
You can try see the following code below:
$(document).ready(function() {
$("button.data-form").on("click", function() {
var action_form = $(this).attr('data');
$("form").attr('id', action_form);
$("form").attr('data', action_form);
$("form#" + action_form).submit(function(event) {
//event.preventDefault();
console.log("co:" + action_form);
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<body>
<form method="post" action="">
<input type="text" name="name" id="name" />
<button class="data-form" data="form-1">Click form 1</button>
<button class="data-form" data="form-2">Click form 2</button>
</form>
</body>

Javascript validation - group validation - if one entered, then all required

Using just jQuery (not validation plugin) I have devised a way to do a "if one, then all" requirement, but it's not at all elegant.
I'm wondering if someone can come up with a more elegant solution? This one uses some loop nesting and I'm really not pleased with it.
if ($("[data-group]")) {
//Store a simple array of objects, each representing one group.
var groups = [];
$("[data-group]").each(function () {
//This function removes an '*' that is placed before the field to validate
removeCurError($(this));
var groupName = $(this).attr('data-group');
//If this group is already in the array, don't add it again
var exists = false;
groups.forEach(function (group) {
if (group.name === groupName)
exists = true;
});
if (!exists) {
var groupElements = $("[data-group='" + groupName + "']");
var group = {
name: groupName,
elements: groupElements,
trigger: false
}
group.elements.each(function () {
if (!group.trigger) {
group.trigger = $(this).val().length !== 0;
}
});
groups.push(group);
}
});
//Now apply the validation and alert the user
groups.forEach(function (group) {
if (group.trigger) {
group.elements.each(function () {
//Make sure it's not the one that's already been filled out
if ($(this).val().length === 0)
// This function adds an '*' to field and puts it into a
// a sting that can be alerted
appendError($(this));
});
}
});
You don't have to store the groups in an array, just call the validateGroups function whenever you want to validate the $elements. Here is a working example http://jsfiddle.net/BBcvk/2/.
HTML
<h2>Group 1</h2>
<div>
<input data-group="group-1" />
</div>
<div>
<input data-group="group-1" />
</div>
<h2>Group 2</h2>
<div>
<input data-group="group-2" value="not empty" />
</div>
<div>
<input data-group="group-2" />
</div>
<div>
<input data-group="group-2" />
</div>
<button>Validate</button>
Javascript
function validateGroups($elements) {
$elements.removeClass('validated');
$elements.each(function() {
// Return if the current element has already been validated.
var $element = $(this);
if ($element.hasClass('validated')) {
return;
}
// Get all elements in the same group.
var groupName = $element.attr('data-group');
var $groupElements = $('[data-group=' + groupName + ']');
var hasOne = false;
// Check to see if any of the elements in the group is not empty.
$groupElements.each(function() {
if ($(this).val().length > 0) {
hasOne = true;
return false;
}
});
// Add an error to each empty element if the group
// has a non-empty element, otherwise remove the error.
$groupElements.each(function() {
var $groupElement = $(this);
if (hasOne && $groupElement.val().length < 1) {
appendError($groupElement);
} else {
removeCurError($groupElement);
}
$groupElement.addClass('validated');
});
});
}
function appendError($element) {
if ($element.next('span.error').length > 0) {
return;
}
$element.after('<span class="error">*</span>');
}
function removeCurError($element) {
$element.next().remove();
}
$(document).ready(function() {
$('button').on('click', function() {
validateGroups($("[data-group]"));
});
});
You might get some milage out of this solution. Basically, simplify and test your solution on submit click before sending the form (which this doesn't do). In this case, I simply test value of the first checkbox for truth, and then alert or check the required boxes. These can be anything you like. Good luck.
http://jsfiddle.net/YD6nW/1/
<form>
<input type="button" onclick="return checkTest()" value="test"/>
</form>
and with jquery:
checkTest = function(){
var isChecked = $('input')[0].checked;
if(isChecked){
alert('form is ready: input 0 is: '+isChecked);
}else{
$('input')[1].checked = true;
$('input')[2].checked = true;
}
};
//create a bunch of checkboxes
$('<input/>', {
type: 'checkbox',
html: 'tick'
}).prependTo('form');
$('<input/>', {
type: 'checkbox',
html: 'tick'
}).prependTo('form');
$('<input/>', {
type: 'checkbox',
html: 'tick'
}).prependTo('form');

JQuery Validated Form Not Submitting

I have a form that I am using on my site and it is validated with some simple JQuery validation. Problem is it's not submitting or doing anything really when I change the values. Here is my code:
<form id="radForm" method="post" action="events.php?type=rad">
<div class="searchBoxLeft searchBoxRad"></div>
<div class="searchBoxMiddle">
<input id="radSearch" type="text" class="searchBoxInput searchBoxShort" value="<?php echo $yourradius; ?>" />
<label class="searchBoxLabel">Mile Radius of Your Address</label>
</div>
<div id="radButton" class="searchBoxRight"></div>
<div class="clearLeft"></div>
</form>
<script>
$(document).ready(function()
{
var radsearchok = 0;
//Rad search
$('#radSearch').blur(function()
{
var radsearch=$("#radSearch").val();
if(radsearch < 2){
$('#radSearch').addClass("searchError");
radsearchok = 0;
}
else if(radsearch > 50){
$('#radSearch').addClass("searchError");
radsearchok = 0;
}
else{
$('#radSearch').addClass("searchSuccess");
radsearchok = 1;
}
});
// Submit button action
$('#radButton').click(function()
{
if(radsearchok == 1)
{
$("#radForm").submit();
}
else
{
$('#radSearch').addClass("searchError");
}
return false;
});
//End
});
</script>
Can anyone see what is wrong with this?
You need to go back and set the .val() property again of your form, otherwise it will take the original value of .val() not radsearch;
Not sure if you actually want to update .val() though or just attach a property. Some options:
Right before the closing brace of .blur --> }); add"
$("#radSearch").val(radsearch);
Or:
Add a hidden input to your form with a new ID like:
<input type='hidden' name='radsearchHidden' />
and then do the same before the end of .blur:
$("#radsearchHidden").val(radsearch);
I made some changes to your code (http://jsfiddle.net/zdeZ2/2/) which I'll describe below:
<div id="radButton" class="searchBoxRight"></div> I assume you have something in there=> <input id="radButton" class="searchBoxRight" type="button" value="rad button">
I rewrote your validator with blur as follows. As suggested it coroses the radSearch value to an integer before comparisions The changes remove the searchError and searchSuccess classes before validating. I also made some optimizations for you.
//Rad search
$('#radSearch').blur(function () {
//remove classes from previous validating
var $this = $(this).removeClass("searchError").removeClass("searchSuccess");
var radsearch = $this.val() | 0; //radsearch is an integer
if (radsearch < 2 || radsearch > 50) {
$this.addClass("searchError");
radsearchok = 0;
} else {
$this.addClass("searchSuccess");
radsearchok = 1;
}
});
Can be equivalently written as:
//Rad search
$('#radSearch').blur(function () {
var $this = $(this);
var radsearch = $("#radSearch").val() | 0; //radsearch is an integer
var valid = radsearch < 2 || radsearch > 50;
$this.toggleClass("searchError", !valid)
.toggleClass("searchSuccess", valid);
radsearchchok = valid ? 1 : 0;
});

Categories

Resources