Categories
JavaScript Answers

How to Watch for Form Data Changes in jQuery?

To watch for form data changes in jQuery, we can listen for input changes.

And when an input value changes, we add the changed data into the form element object.

For instance, if we have the following form:

<form>
  <input>
  <button type='submit' id='mybutton'>
    submit
  </button>
</form>

Then we can listen for changes of the input by writing:

$("form :input").change(function() {
  $(this).closest('form').data('changed', true);
});

$('#mybutton').click(function() {
  if ($(this).closest('form').data('changed')) {
    console.log('form changed')
  }
});

We select the input elements in the form with $(“form :input”) .

Then we call change on it with a callback that gets the closest form element of the input.

And we call data with the 'changed' key and true as the value of the key.

Next, we get the button with ID mybutton with $(‘#mybutton’) .

We call click on it to listen to click events on it.

We call it with a callback that gets the form with $(this).closest(‘form’) .

And we get the 'changed' data value from the form element object with the data method.

If the input value changed and we click the button, we should see 'form changed' logged.

Categories
JavaScript Answers

How to Abort a Previous AJAX Request on a New Request with jQuery?

To abort a previous Ajax request on a new request with jQuery, we can call the abort method on the request object.

For instance, we can write:

const currentRequest = $.ajax({
  type: 'GET',
  url: 'https://yesno.wtf/api',
})

$.ajax({
  type: 'GET',
  url: 'https://yesno.wtf/api',
  beforeSend: () => {
    currentRequest.abort();
  },
  success: (data) => {
    // Success
  },
  error: (e) => {
    // Error
  }
});

We create the currentRequest object with the $.ajax method to make the request.

Then in the 2nd ajax call, we call currentRequest.abort in the beforeSend method.

The abort method will cancel the request made in the first ajax call.

We also have the success method that runs when the request is successful.

And the error method runs when there’s an error with the request.

Categories
JavaScript Answers

How to Check if the Array of Objects Have Duplicate Property Values with JavaScript?

To check if the array of objects have duplicate property values with JavaScript, we can use the JavaScript array’s map and some method to map the array to the property values we want to check.

Then we can use the indexOf method in the some callback to check if an element in the mapped array is the first instance or not.

For instance, we can write:

const values = [{
    name: 'someName1'
  },
  {
    name: 'someName2'
  },
  {
    name: 'someName4'
  },
  {
    name: 'someName2'
  }
];

const valueArr = values.map((item) => {
  return item.name
});
const isDuplicate = valueArr.some((item, idx) => {
  return valueArr.indexOf(item) !== idx
});
console.log(isDuplicate);

We have the values array that we want to check if there’re duplicate values of the name property.

Then we call map to return an array with the name property values and assign it to valueArr .

Next, we call valueArr.some with a callback that checks if idx is different from the index returned by indexOf .

Since indexOf returns the index of the first instance of a value, that means if idx is different from what’s returned with indexOf , we know it’s a duplicate value.

Therefore, since we have a duplicate value of name in 2 entries, isDuplicate is true and that’s logged in the console log.

Categories
JavaScript Answers

How to Get a JSON Object’s Key and Value in JavaScript?

To get a JSON object’s key and value in JavaScript, we can use the JSON.parse method to parse the JSON object string into a JavaScript object.

Then we can get a property’s value as we do with any other JavaScript object.

For instance, we can write:

const data = `{
  "name": "",
  "skills": "",
  "jobtitel": "Entwickler",
  "res_linkedin": "webSearch"
}`

const parsedData = JSON.parse(data);
console.log(parsedData.name);
console.log(parsedData.skills);
console.log(parsedData.jobtitel);
console.log(parsedData.res_linkedin);

We have the data JSON string that we parse into an object with JSON.parse and assigned it to parsedData .

Then we can get the properties from parsedData with the dot notation as we do with any other JavaScript object.

Categories
JavaScript Answers

How to Check if a String is JSON in JavaScript?

To check if a string is JSON in JavaScript, we can use the JSON.parse method within a try-catch block.

For instance, we can write:

const jsonStr = JSON.stringify({  
  foo: 'bar'  
})  
try {  
  const json = JSON.parse(jsonStr);  
} catch (e) {  
  console.log('invalid json');  
}

to check if jsonStr is a valid JSON string.

Since we created the JSON string by calling JSON.stringify with an object, it should be valid JSON.

Next, we have a try-catch block with the JSON.parse call in the try block to try to parse the jsonStr string with JSON.parse .

Since jsonStr is a valid JSON string, the code in the catch block shouldn’t run.

If jsonStr isn’t a valid JSON string, then the code in the catch block runs since JSON.parse will throw an exception if it’s called with an invalid JSON string.