Skip to content

Commit

Permalink
fix(form): fixed common form get value selector
Browse files Browse the repository at this point in the history
close #1178
  • Loading branch information
munkhorgil authored and batamar committed Aug 14, 2019
1 parent aaf0eb9 commit 813acf6
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 14 deletions.
27 changes: 13 additions & 14 deletions src/modules/common/components/form/Form.tsx
@@ -1,7 +1,7 @@
import { IFormProps } from 'modules/common/types';
import React from 'react';
import validator from 'validator';
import { __ } from '../../utils';
import { __, generateRandomString } from '../../utils';
import { Error } from './styles';

type Props = {
Expand All @@ -16,6 +16,7 @@ type State = {
};

class Form extends React.Component<Props, State> {
private formId: string = generateRandomString();
private children: any[] = [];

constructor(props: Props) {
Expand Down Expand Up @@ -56,16 +57,18 @@ class Form extends React.Component<Props, State> {
});
};

getValue = child => {
const { name } = child.props;
getSelector = (name: string) => {
return document.querySelector(`#${this.formId} [name='${name}']`) as any;
};

const values = document.getElementsByName(name) as any;
getValue = child => {
const element = this.getSelector(child.props.name);

if (values.length > 1) {
return values[values.length - 1].value;
if (element) {
return element.value;
}

return values[0].value;
return '';
};

onSubmit = e => {
Expand All @@ -77,12 +80,8 @@ class Form extends React.Component<Props, State> {

validate = child => {
const { props } = child;
const elements = document.getElementsByName(props.name) as any;

const value =
elements.length > 1
? elements[elements.length - 1].value
: elements[0].value;
const element = this.getSelector(props.name);
const value = element ? element.value : '';

if (props.required && !value) {
return <Error>{__('Required field')}</Error>;
Expand Down Expand Up @@ -124,7 +123,7 @@ class Form extends React.Component<Props, State> {

render() {
return (
<form onSubmit={this.onSubmit} noValidate={true}>
<form id={this.formId} onSubmit={this.onSubmit} noValidate={true}>
{this.props.renderContent({
errors: this.state.errors,
values: this.state.values,
Expand Down
16 changes: 16 additions & 0 deletions src/modules/common/utils/index.tsx
Expand Up @@ -214,3 +214,19 @@ export const getCookie = cname => {

return '';
};

/**
* Generate random string
*/
export const generateRandomString = (len: number = 10) => {
const charSet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';

let randomString = '';

for (let i = 0; i < len; i++) {
const position = Math.floor(Math.random() * charSet.length);
randomString += charSet.substring(position, position + 1);
}

return randomString;
};

0 comments on commit 813acf6

Please sign in to comment.