Thursday, December 31, 2020

Send user to a new url with parameter using React

Here is the scenario - You need update the page view when a user makes a selection from a drop down. Example: There is a drop down of employees and when the user makes a selection, you need to change the employee profile view to the selected employee.

First, you can pass a url parameter like so:   /yourUrl/2202.

You then read the parameter in the code like so: props.match.params.id

EX:     

let emp_id = {
      emp_id: props.match.params.id,
    };


SIDE NOTE: You will need to add match to propTypes and you do that like so:

  match: PropTypes.shape({
    params: PropTypes.shape({
      id: PropTypes.string,
    }),
  })

You also need to pass it in App.js like so: 

<Route path="/yourUrl/:id" component={YourComponent} />

Now that you have passed in your parameter, you can use it to get the employee info from the database. In this case, I am using useEffect. I create an argument from the ID passed in (see green text below) and then I pass the emp_id into my function to get the data for the employee (see blue text below). The red text below will call this function only if the ID has changed.

  useEffect(() => {

    let emp_id = {
      emp_id: props.match.params.id,
    };

    props.loadEmployee(emp_id);
  

  }, [props.match.params.id]);


Ok so now, lets add in a select function so the user can change the employee.

Simply add a select drop down like so:

<ValidationForm onSubmit={handleSubmit}>
<SelectGroup
  name="emp_id"
  id="emp_id"
  value={props.match.params.id}
  onChange={handleEmployeeChange.bind(this)}
>
  <option value=""></option>
  {props.employees.map((e, key) => {
return (
  <option key={key} value={e.employee_emp_id}>
{e.employee_name} ({e.employee_emp_id})
  </option>
);
  })}
</SelectGroup>
  </ValidationForm>

Ok let's walk through this code. 
  1. The blue line defaults the selection to the current url param.
  2. The red line handles the change
  3. The orange lines populate the drop down
Now, the red line calls another function and binds the selected employee ID. When the user makes a selection, here is the handleEmployeeChange function that is called:

 const handleEmployeeChange = (event) => {
    props.history.push(`/yourUrl/${event.target.value}`);
  };


handleEmployeeChange takes the selected value and calls the url which will load the data of the newly selected employee.

SIDE NOTE:  You can learn more about props.history.push here

That's it!

Let me know if you have any questions or suggestion of a better way!

Tuesday, August 14, 2018

How to require at least one checkbox

Here is your script:


<script>
            $(document).ready(function () {
                $('#checkBtn').click(function() {
                  checked = $("input[type=checkbox]:checked").length;

                  if(!checked) {
                    alert("You must check at least one record.");
                    return false;
                  }

                });
            });
</script>
            

Add this to your submit button:

 id="checkBtn"

Thursday, March 22, 2018

Turn Off Auto-Complete for all browsers

While we all love the auto-complete function on browsers, there may be a reason to turn it off.  Mainly, for security reasons, like on banking sites.

This is a hack and the only solution that will work on all browsers. 

Add the following to all fields that you don't want to auto-fill:

readonly onfocus="this.removeAttribute('readonly');" style="background-color:white;"

What happens is, when the page loads, the fields are read only. Once the user clicks on the field to enter a value, the readonly attribute is removed.

Now, an important part of this is to make sure you add a white background so the fields don't appear to be readonly.

That's it!

nJoy.

Thursday, March 8, 2018

How to keep a user's session alive

There may be instances where you need to keep a user's session alive. For example, your visitors need to take an hour long course, but the global session timeout is 30 minutes. You don't want the user's session to time out before they finish the course, right?

Here is a simple way to keep the session alive.

Add this script to the very top of the pages. Then, add a blank page in the same directory. Notice the bold red line below - I have a 'keep_alive.cfm" file in the same directory, which is accessed by the script which in turn keeps the session alive.

<script>
    var xmlhttp;
setInterval
    (
        function() {
            if (window.XMLHttpRequest) {
                // code for IE7+, Firefox, Chrome, Opera, Safari
                xmlhttp = new XMLHttpRequest();
            } else {
                // code for IE6, IE5
                xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
            }
            xmlhttp.open("POST", "keep_alive.cfm", true);
            xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
            xmlhttp.send("foo=bar");
        }, 60000
); // 1 minute
</script>



Enjoy!

Wednesday, February 21, 2018

Quick and easy way to hide and show items on a page with JavaScript



In this scenario, we want to hide/show salary questions IF the user is in certain states:


Step 1: The Form

Form Fields: I added an onClick event to the radio buttons which will kick off the SHOW/HIDE function: 

<input type="radio" value="0" onclick="javascript:showHideSalary();" id="legalStates0" name="legalStates"> NO

<input type="radio" value="1" onclick="javascript:showHideSalary();" id="legalStates1" name="legalStates"> YES





Step 2: The script

Add this script to the top of the page. Here I am saying if the users selects YES to the legal states question, hide the salary div.

<script>
function showHideSalary() {
    if (document.getElementById('legalStates0').checked){
        document.getElementById('salaryDiv').style.display = 'block';  display it
    }
    else document.getElementById('salaryDiv').style.display = 'none'; don't display it

}
</script>




Step 3: The DIV you want to hide. 


<div id="salaryDiv" style="display:none">

* add whatever you want to hide/display here *

</div>


Enjoy and let me know if you have any issues.


Tuesday, October 3, 2017

Bootstrap: Collapse panel with radio buttons

There are many examples of this code that don't have the radio button actually selected.

Here is the code that does so:



<!DOCTYPE html>
<html >
<head>
  <meta charset="UTF-8">
  <title>Bootstrap: Collapse panel with radio buttons</title>
   
   
  <link rel='stylesheet prefetch' href='http://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css'>

      <link rel="stylesheet" href="css/style.css">

   
</head>

<body>
  <h2>Bootstrap: Collapse panel with radio buttons</h2>
<i>A simple method to collapse and expand a Bootstrap collapsable panel using radio buttons</i>

<div class="container">
  <div class="row">
    <div class="col-xs-12">
      <span>Display panel: </span>
      <input name="collapseGroup" type="radio" data-toggle="collapse" data-target="#collapseOne"/> Yes
      <input name="collapseGroup" type="radio" data-toggle="collapse" data-target="#collapseOne" checked/> No
      <div class="panel-group" id="accordion">
        <div class="panel panel-default">
          <div class="panel-heading">
            <h4 class="panel-title">
              Header
            </h4>
          </div>
          <div id="collapseOne" class="panel-collapse collapse">
            <div class="panel-body">
              <p>Content</p>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>
  <script src='http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script>
<script src='https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js'></script>

   
</body>
</html>

Friday, August 4, 2017

Find a specific column and/or table in SQL

I'll make this quick and just share the query:

SELECT       c.name  AS 'ColumnName',t.name AS 'TableName'
FROM          sys.columns c
JOIN             sys.tables  t   ON c.object_id = t.object_id
WHERE        c.name LIKE '%addNameHere%'
ORDER BY  TableName   ,ColumnName;


Enjoy!